How would you implement different types of errors, so you'd be able to catch specific ones and let others bubble up..?
One way to achieve this is to modify the prototype of the Error
object:
Error.prototype.sender = "";
function throwSpecificError()
{
var e = new Error();
e.sender = "specific";
throw e;
}
Catch specific error:
try
{
throwSpecificError();
}
catch (e)
{
if (e.sender !== "specific") throw e;
// handle specific error
}
Have you guys got any alternatives?
As noted in the comments below this is Mozilla specific, but you can use 'conditional catch' blocks. e.g.:
This gives something more akin to typed exception handling used in Java, at least syntactically.
try-catch-finally.js
Example
To create custom exceptions, you can inherit from the Error object:
A minimalistic approach, without inheriting from Error, could be throwing a simple object having a name and a message properties: