12

I'm about to throw an exception using RangeError and wanted to check that I'm using it correctly and how to best catch it.

I have a function that could throw a RangeError OR a TypeError like this

function saveNumber(val) {
  // Only accept numbers.
  if (typeof val !== 'number') {
    throw new TypeError();
  }

  // Error if the number is outside of the range.
  if (val > max || val < min) {
    throw new RangeError();
  }

  db.save(val);
}

I'd like to call it and only deal with the RangeError. What's the best way to do this?

2
  • Just don't throw a TypeError? Commented Dec 3, 2013 at 15:45
  • another piece of code may want to call this function and deal with the TypeError Commented Dec 3, 2013 at 15:45

3 Answers 3

12
try {
  saveNumber(...);
} catch (e) {
  if (e instanceof TypeError) {
    // ignore TypeError
  } 
  else if(e instanceof RangeError) {
    // handle RangeError
  }
  else {
    // something else
  } 
}

source

Sign up to request clarification or add additional context in comments.

1 Comment

In general you need to re-throw if you don't handle.
3

Straight from the MDN documentation on try - catch:

try {
    saveNumber(...);
} catch (e is instanceof RangeError) {
    // Do something
} catch (e) {
    // re-throw whatever you don't want to handle
    throw e;
}

2 Comments

JS Hint is complaining 'catch filter' is only available in Mozilla JavaScript extensions (use moz option)'. So it's a nice answer but not fully compatible.
From the same docs: "Reminder: this functionality is not part of the ECMAScript specification."
2

slightly more elegant answer:

switch (error.constructor) {
    case NotAllowedError:
        return res.send(400);
    case NotFoundError:
        return res.send(404);
    default:
        return res.send(500);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.