Reputation: 17604
Throw InvalidArgumentException in a JavaScript method like one does in Java or similar languages.
I have been trying to familiarize myself with JavaSctipt error handling, and I know I can throw exceptions using the throw
keyword.
To achieve this, I read the throw documentation on MDN and the Error documentation on MDN as well.
So far this is my code:
if (mySize >= myArray.length)
throw new Error("InvalidArgumentExcpetion - BANG!!!!");
This code has some problems for me:
So now I am confused.
Upvotes: 20
Views: 30650
Reputation: 10109
I have been trying to familiarize myself with JavaSctipt [sic] error handling, and I know I can throw exceptions [....] but tomorrow I may want BONG [....]
You could throw a TypeError
or a SyntaxError
if they make more sense. But no need to get too fancy. Simply throw an Error
with a message as it looks as though you're already doing:
if (myArray && myArray.length < mySize) throw new Error('`mySize` must be larger');
And if you decide tomorrow you want BONG:
if (!myBong) throw new Error('Officer, that is not `myBong`');
For more info on built-in errors types, read the docs.
Upvotes: 9
Reputation: 11601
Please see the answer below:
If you want to handle exceptions based on their types like in Java, you should create a new object like in the document.
If you don't want to look for the message everywhere, create a new error list like you do in Java. For instance:
let errors = {
invalidOperation: 'Invalid operation',
unAuthorized: 'You are not authorized to use this function',
}
and use them instead of hard-coded strings like
throw new InvalidOperationException(errors.invalidOperation);
JavaScript does not have InvalidArgumentException.
Upvotes: 9
Reputation: 17604
After doing research, I now have come down to a solution that I like. Special kudos to Toan, I would gladly chose his answer, but since I do feel that it is still a little bit incomplete, I decided to create my own answer with my own findings. Hope it helps someone !
Using the solution proposed by Toan: https://stackoverflow.com/a/38146237/1337392
It is a possible, albeit if you want customization you do need to create your own object.
Thanks for all the help guys! kudos++ for all!
Upvotes: 18