views:

194

answers:

2

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?

+4  A: 

You can use 'conditional catch' blocks. e.g.:

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 akin to typed exception handling used in Java, at least syntactically.

Andy
Combine with CMS's answer and it's perfect.
Ates Goral
Conditional catch is something I either didn't know earlier or forgot about. Thanks for educating/reminding me! +1
Ates Goral
Only supported by Firefox (since 2.0). It does not even parse in other browsers; you only get syntax errors.
Crescent Fresh
Yes, this is a Mozilla-only extension, it's not even proposed for standardisation. Being a syntax-level feature there's no way to sniff for it and optionally use it either.
bobince
+10  A: 

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

function SpecificError () {

}

SpecificError.prototype = new Error();

// ...
try {
  throw new SpecificError;
} catch (e) {
  if (e instanceof SpecificError) {
   // specific error
  }
}

A minimalistic approach, without inheriting from Error, could be throwing a simple object having a name and a message properties:

function throwSpecificError() {
  throw {
    name: 'SpecificError',
    message: 'SpecificError occurred!'
  };
}


// ...
try {
  throwSpecificError();
} catch (e) {
  if (e.name == 'SpecificError') {
   // specific error
  }
}
CMS
Nice :)
Thiyagaraj
Combine with Andrew's answer and it's perfect.
Ates Goral
Inheriting from `Error` has problems. See http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/1382129#1382129
Crescent Fresh