最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

try catch - Using and catching RangeError in javascript - Stack Overflow

programmeradmin2浏览0评论

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);
}
发布评论

评论列表(0)

  1. 暂无评论