Using and capturing RangeError in javascript

I am going to throw an exception with RangeError and want to check if I use it correctly and how to catch it better.

I have a function that can throw a RangeError OR 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 would like to call it and only deal with RangeError. What is the best way to do this?

+7
javascript try-catch
source share
3 answers
 try { saveNumber(...); } catch (e) { if (e instanceof TypeError) { // ignore TypeError } else if(e instanceof RangeError) { // handle RangeError } else { // something else } } 

a source

+8
source share

Straight from the MDN try-catch documentation :

 try { saveNumber(...); } catch (e if e is instanceof RangeError) { // Do something } catch (e) { // re-throw whatever you don't want to handle throw e; } 
+2
source share

slightly more elegant answer:

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

All Articles