捕获抛出的枚举值
Catching thrown Enum Values
Haxe 几乎可以投掷任何东西,但它的接球能力似乎有点受限。例如,我有一个抛出 ErrorType 枚举值的静态错误函数:
class Error
{
public static var CATCH_ALL:Bool = false;
public static function Throw(aError:ErrorType, ?ignore:Bool=false, ?inf:PosInfos):Void
{
trace('Error: $aError at ' + inf.className + ':' + inf.methodName + ':' + inf.lineNumber);
if (!CATCH_ALL && !ignore)
{
throw aError;
}
}
}
enum ErrorType
{
NULL_PARAM(msg:String);
NOT_FOUND(msg:String);
}
虽然我几乎可以捕获任何东西,但我仅限于基本类型、class 类型和枚举类型。这意味着我可以捕获每个字符串,但不是特定的包含 "potato" 的字符串。如果我创建多个错误 classes,我可以捕获特定的 class 类型而忽略其他类型,但枚举似乎不可能实现同样的事情。是否可以替代以下可编译的代码?
try
{
Error.Throw(ErrorType.NULL_PARAM('Potato'));
}
catch (e:ErrorType.NULL_PARAM) trace(e); //does not work nor compile
catch (e:ErrorType) trace(e); //works, but catches every error
catch
-表达式的选择是 limited to types/不提供像 switch
那样的模式匹配功能:
Catch blocks are checked from top to bottom with the first one whose type is compatible with the thrown value being picked.
ErrorType
枚举的所有 值 都与 ErrorType
类型 兼容。这意味着不幸的是,我认为你能做的最好的事情是捕获 ErrorType
然后在捕获块内进行选择,使用 switch
并可能重新抛出它。但是,请注意,简单的 throw e
当前会导致堆栈跟踪丢失,如 #4159.
中所述
Haxe 几乎可以投掷任何东西,但它的接球能力似乎有点受限。例如,我有一个抛出 ErrorType 枚举值的静态错误函数:
class Error
{
public static var CATCH_ALL:Bool = false;
public static function Throw(aError:ErrorType, ?ignore:Bool=false, ?inf:PosInfos):Void
{
trace('Error: $aError at ' + inf.className + ':' + inf.methodName + ':' + inf.lineNumber);
if (!CATCH_ALL && !ignore)
{
throw aError;
}
}
}
enum ErrorType
{
NULL_PARAM(msg:String);
NOT_FOUND(msg:String);
}
虽然我几乎可以捕获任何东西,但我仅限于基本类型、class 类型和枚举类型。这意味着我可以捕获每个字符串,但不是特定的包含 "potato" 的字符串。如果我创建多个错误 classes,我可以捕获特定的 class 类型而忽略其他类型,但枚举似乎不可能实现同样的事情。是否可以替代以下可编译的代码?
try
{
Error.Throw(ErrorType.NULL_PARAM('Potato'));
}
catch (e:ErrorType.NULL_PARAM) trace(e); //does not work nor compile
catch (e:ErrorType) trace(e); //works, but catches every error
catch
-表达式的选择是 limited to types/不提供像 switch
那样的模式匹配功能:
Catch blocks are checked from top to bottom with the first one whose type is compatible with the thrown value being picked.
ErrorType
枚举的所有 值 都与 ErrorType
类型 兼容。这意味着不幸的是,我认为你能做的最好的事情是捕获 ErrorType
然后在捕获块内进行选择,使用 switch
并可能重新抛出它。但是,请注意,简单的 throw e
当前会导致堆栈跟踪丢失,如 #4159.