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
3 Answers
Reset to default 12try {
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
版权声明:本文标题:try catch - Using and catching RangeError in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738746416a2110144.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论