我正在使用TypeScript进行一个相当大的项目,我想知道使用错误的标准是什么。例如,我在Java中抛出了一个索引越界异常:

throw new IndexOutOfBoundsException();

在TypeScript中等价的语句是:

throw new Error("Index Out of Bounds");

还有什么其他方法可以实现这个目标?公认的标准是什么?


JavaScript中对于超出范围的约定是使用RangeError。要检查类型,请使用if / else + instanceof从最特定的最通用的开始

try {
    throw new RangeError();
}
catch (e){
    if (e instanceof RangeError){
        console.log('out of range');
    } else { 
        throw; 
    }
}

有人在评论中发布了这个MDN的链接,我认为这很有帮助。它非常全面地描述了ErrorTypes之类的东西。

EvalError --- Creates an instance representing an error that occurs regarding the global function eval(). InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion". RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference. SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval(). TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.


通过异常发出和显示消息的简单解决方案。

try {
  throw new TypeError("Error message");
}
catch (e){
  console.log((<Error>e).message);//conversion to Error type
}

谨慎

如果我们不知道可以从块中发出什么样的错误,上面不是一个解决方案。在这种情况下,应该使用类型保护,并对适当的错误进行适当的处理-看看@Moriarty的回答。


不要忘记switch语句:

确保默认处理。 Instanceof可以在超类上匹配。 ES6构造函数将匹配精确的类。 更容易阅读。

函数handleError() 尝试{ throw new RangeError(); } Catch (e) { Switch (e.constructor) { 返回console.log('generic'); 返回console.log('range'); 默认值:返回console.log('unknown'); } } } handleError ();