Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using and catching RangeError in javascript

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?

like image 898
eddiec Avatar asked Dec 03 '13 15:12

eddiec


People also ask

What is RangeError JavaScript?

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.

How do you fix a range error?

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.


3 Answers

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;
}
like image 166
Justin Niessner Avatar answered Oct 18 '22 08:10

Justin Niessner


slightly more elegant answer:

switch (error.constructor) {
    case NotAllowedError:
        return res.send(400);
    case NotFoundError:
        return res.send(404);
    default:
        return res.send(500);
}
like image 41
Anona112 Avatar answered Oct 18 '22 09:10

Anona112


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

source

like image 36
qwertynl Avatar answered Oct 18 '22 08:10

qwertynl