Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use case for throwing a non-Error object? [closed]

In JS you can throw new Error(), throw 'foo' or even throw null.

Why would you want to throw a non-Error instance? I don't mean objects that inherit from Error--I mean other random objects or primitives.

like image 745
boneskull Avatar asked Jun 30 '15 02:06

boneskull


1 Answers

throw just throws an arbitrary expression. It is not connected to the Error object in any way; you can throw any expression.

But it's probably a better idea to inherit from the Error object, which is exactly what the other standard built-in errors do:

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.

All of these objects prototypically inherit from the Error object, so while it's legal to throw any arbitrary object, it probably makes more sense to throw the Error object or an object that inherits from Error, just like Javascript itself does.

There are several examples of the proper way to do this at this MDN page.

like image 161
Robert Harvey Avatar answered Sep 27 '22 17:09

Robert Harvey