What is the use case for throwing an object without errors?

In JS, you can throw new Error()

, throw 'foo'

or even throw null

.

Why do you want to throw a non copy Error

? I don't mean objects that inherit from Error

- I mean other random objects or primitives.

+3


source to share


1 answer


throw

just produces an arbitrary expression . It has nothing to do with the Error

object
; you can throw

any expression.

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

EvalError
Creates an instance representing the error that is thrown against the global function eval ().

InternalError Creates an instance representing the error that is thrown when an internal error occurs in the JavaScript engine. For example. "too much recursion".

RangeError
Creates an instance representing the error that occurs when a numeric variable or parameter is out of range.

ReferenceError
Creates an instance that represents the error that occurs when a reference to an invalid reference is deleted.



SyntaxError
Creates an instance that represents a syntax error that occurs when code is parsed in eval ().

TypeError
Creates an instance that represents the error that occurs when a variable or parameter is not of a valid type.

URIError
Creates an instance that represents an error that occurs when invalid parameters are passed to encodeURI () or decodeURI ().

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

There are several examples of the correct way to do this on this MDN page .

+2


source







All Articles