Handling specific errors in JavaScript (read exceptions)

How would you implement different types of errors so that you can catch specific ones and let others bubble up ...?

One way to achieve this is to change the prototype of the Error object:

 Error.prototype.sender = ""; function throwSpecificError() { var e = new Error(); e.sender = "specific"; throw e; } 

Error specific error:

 try { throwSpecificError(); } catch (e) { if (e.sender !== "specific") throw e; // handle specific error } 


Do you have any alternatives?

+51
javascript error-handling
Sep 16 '09 at 15:00
source share
3 answers

To create custom exceptions, you can inherit the Error object:

 function SpecificError () { } SpecificError.prototype = new Error(); // ... try { throw new SpecificError; } catch (e) { if (e instanceof SpecificError) { // specific error } else { throw e; // let others bubble up } } 

A minimalistic approach that does not inherit from Error can call a simple object with the name and properties of the message:

 function throwSpecificError() { throw { name: 'SpecificError', message: 'SpecificError occurred!' }; } // ... try { throwSpecificError(); } catch (e) { if (e.name == 'SpecificError') { // specific error } else { throw e; // let others bubble up } } 
+72
16 Sep '09 at 15:09
source share

As noted in the comments below, this is a Mozilla specification, but you can use conditional catch blocks. eg:.

 try { ... throwSpecificError(); ... } catch (e if e.sender === "specific") { specificHandler(e); } catch (e if e.sender === "unspecific") { unspecificHandler(e); } catch (e) { // don't know what to do throw e; } 

This gives something more like the typed exception handling used in Java, at least syntactically.

+11
Sep 16 '09 at 15:08
source share

try-catch-finally.js

Example

 _try(function () { throw 'My error'; }) .catch(Error, function (e) { console.log('Caught Error: ' + e); }) .catch(String, function (e) { console.log('Caught String: ' + e); }) .catch(function (e) { console.log('Caught other: ' + e); }) .finally(function () { console.log('Error was caught explicitly'); }); 
+6
Jan 17 '13 at 17:49
source share



All Articles