admin管理员组

文章数量:1208155

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?

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?

Share Improve this question asked Dec 3, 2013 at 15:44 eddieceddiec 7,6465 gold badges35 silver badges36 bronze badges 2
  • Just don't throw a TypeError? – qwertynl Commented Dec 3, 2013 at 15:45
  • another piece of code may want to call this function and deal with the TypeError – eddiec Commented Dec 3, 2013 at 15:45
Add a comment  | 

3 Answers 3

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

source

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;
}

slightly more elegant answer:

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

本文标签: try catchUsing and catching RangeError in javascriptStack Overflow