03 Conditional Catch

Sometimes you may need to have one or more conditional catch clauses to handle specific exceptions:

try {
  myroutine(); // may throw three types of exceptions
} catch (e) {
  if (e instanceof TypeError) {
    // statements to handle TypeError exceptions
  } else if (e instanceof RangeError) {
    // statements to handle RangeError exceptions
  } else if (e instanceof EvalError) {
    // statements to handle EvalError exceptions
  } else {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
  }
}

Guard for exceptions

JavaScript catch doesn't support any mechanism to filter errors. This limitation isn't too hard to get around: we can write a function guard():

function guard(e, predicate) {
  if (!predicate(e)) throw e;
}

And then use it to e.g. only filter "not found" errors when downloading an image:

try {
    await downloadImage(url);
} catch (e) {
    guard(e, e => e.code == 404);
    handle404(...);
}

Last updated