Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing custom exceptions in Javascript. Which style to use?

Tags:

Douglas Crockford recommends doing something like this:

throw {     name: "System Error",     message: "Something horrible happened." }; 

But you could also do something like this:

function IllegalArgumentException(message) {     this.message = message; }  throw new IllegalArgumentException("Argument cannot be less than zero"); 

and then do:

try {     //some code that generates exceptions } catch(e) {         if(e instanceof IllegalArgumentException) {         //handle this     } else if(e instanceof SomeOtherTypeOfException) {         //handle this     } } 

I guess you could include a type property in Crockford's implementation and then examine that instead of doing an instanceof. Is there any advantage from doing one versus the other?

like image 758
Vivin Paliath Avatar asked Oct 25 '12 21:10

Vivin Paliath


People also ask

Can you throw exceptions in JavaScript?

Technically you can throw an exception (throw an error). If you use throw together with try and catch , you can control program flow and generate custom error messages.

What's the difference between throw error (' MSG ') vs throw new error (' MSG ')?

throw new Error() Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stack traces. throw Error() is like a Javascript string, a number, a boolean, or an object. It returns specific errors as defined in the message value which is passed as an argument.


1 Answers

Please note that meanwhile most of the JavaScripts environments provide the Error object as basis for exceptions. It already allows you to define a message, but also provides a useful stack property to track down the context of the exception. You can create your own exception type by using prototypical inheritance. There are already several stackoverflow discussions (for example: here), how to do this properly. However, I had to dig a little bit until I found the correct and modern approach. Please be aware that the approach that is suggested in the Mozilla documentation (see above) is not liked by the stackoverflow community. After a lot of reading I came out with that approach for inherit from Error.prototype:

function IllegalArgumentException(sMessage) {     this.name = "IllegalArgumentException";     this.message = sMessage;     this.stack = (new Error()).stack; } IllegalArgumentException.prototype = Object.create(Error.prototype); IllegalArgumentException.prototype.constructor = IllegalArgumentException; 
like image 130
rene Avatar answered Sep 28 '22 06:09

rene