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?

eddiec
  • 7,608
  • 5
  • 34
  • 36

3 Answers3

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

source

Community
  • 1
  • 1
qwertynl
  • 3,912
  • 1
  • 21
  • 43
4

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;
}
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 2
    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. – eddiec Dec 03 '13 at 16:09
  • From the same docs: "Reminder: this functionality is not part of the ECMAScript specification." – Pavlo Jul 13 '16 at 12:21
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);
}
Anona112
  • 3,724
  • 4
  • 21
  • 30