Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an idiomatic way to handle illegal argument in JavaScript?

Let's say I have a function that accepts only non-negative numbers and I receive a negative argument.

In Python, I would raise a ValueError. In Java, I would throw an IllegalArgumentException. Is there any built-in exception I should throw in JavaScript, or should I return undefined?

like image 623
prasopes Avatar asked Oct 21 '22 17:10

prasopes


1 Answers

This is a common asked question: To throw an exception, or to return?

I suggest you see this: https://stackoverflow.com/a/1153149/2557927

If your method can't do what its name says it does, throw.

According to MDN, you probably wanted to throw RangeError("x should be a non-negative number");. Although JavaScript does not limit the data type of what can be thrown, I think that throwing a Error class is better than throwing a string since it is easier to be caught by uplevel functions.

like image 98
Star Brilliant Avatar answered Nov 15 '22 00:11

Star Brilliant