Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of exception should be thrown in JavaScript?

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?

like image 583
Motti Avatar asked Nov 08 '10 12:11

Motti


1 Answers

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:

  • Consistency with handling errors thrown by native code, such as having a 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.
like image 182
Tim Down Avatar answered Sep 29 '22 23:09

Tim Down