Proper use of errors

拥有回忆 提交于 2020-01-22 04:07:31

问题


I'm using TypeScript for a reasonably large project, and am wondering what the standard is for the use of Errors. For example, say I hand an index out of bounds exception in Java:

throw new IndexOutOfBoundsException();

Would the equivalent statement in TypeScript be:

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

What other ways could I accomplish this? What is the accepted standard?


回答1:


Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

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.




回答2:


The convention for out of range in JavaScript is using RangeError. To check the type use if / else + instanceof starting at the most specific to the most generic

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



回答3:


Simple solution to emit and show message by Exception.

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

Caution

Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.




回答4:


Don't forget about switch statements:

  • Ensure handling with default.
  • instanceof can match on superclass.
  • ES6 constructor will match on the exact class.
  • Easier to read.

function handleError() {
    try {
        throw new RangeError();
    }
    catch (e) {
        switch (e.constructor) {
            case Error:      return console.log('generic');
            case RangeError: return console.log('range');
            default:         return console.log('unknown');
        }
    }
}

handleError();


来源:https://stackoverflow.com/questions/23790509/proper-use-of-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!