What type of object should be thrown in JavaScript?
I see a lot of examples which throw a plain old string
and there seems to be a semi-standard Error
type. Should I prefer one over the other?
The Error
object and specific error objects such as TypeError
are fully standardized in the ECMAScript specification. There are, however, common non-standard properties of these objects available in most browsers.
You can throw whatever you like, so long as your error handling code knows what to do with the objects you throw, but there are advantages to using Error
objects:
message
property, so you don't have to write different code to handle native errors and your own errors;Error
objects in Mozilla and other browsers have very useful non-standard properties, such as fileName
, lineNumber
and stack
. You only get these on Error
objects and they can be very useful for debugging.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With