I'm using TypeScript for a reasonably large project, and am wondering what the standard is for the use of Error
s. 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?
This question is related to
exception
typescript
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
}
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.
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');
} else {
throw;
}
}
Don't forget about switch statements:
default
.instanceof
can match on superclass.constructor
will match on the exact class.function handleError() {_x000D_
try {_x000D_
throw new RangeError();_x000D_
}_x000D_
catch (e) {_x000D_
switch (e.constructor) {_x000D_
case Error: return console.log('generic');_x000D_
case RangeError: return console.log('range');_x000D_
default: return console.log('unknown');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
handleError();
_x000D_
Source: Stackoverflow.com