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?
A RangeError is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value. This can be encountered when: passing a value that is not one of the allowed string values to String.
The most common way to fix this error is to reduce the number of function calls, or to limit the number of variables that are created. Another option is to use a tracer debugger to keep track of the program's state and find the function that's causing the error.
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 {
saveNumber(...);
} catch (e) {
if (e instanceof TypeError) {
// ignore TypeError
}
else if(e instanceof RangeError) {
// handle RangeError
}
else {
// something else
}
}
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With