5

I'm Java developer and I'm now learning Javascript creating a personal project. I don't know how to handle different errors in Javascript in a clean way and I can't find a good solution on the web.

I'm consuming some external APIs using axios. The external resource use a pagination system, so when I get back a 204 status code means that there are not more pages to consume, so I've to perform a different action than the others error.

In Java I would have created a MyException class and added another catch. How to do in Javascript?

I don't really like how I do it. There's a better or cleaner way to do it? Maybe I should save 'NO_PAGE' as global constant? Here is a code example:

const myFunc = async () => {
 try {
 //... Some code using axios
 } catch (error) {
 if (error.request._currentRequest.res.statusCode === 204) {
 throw Error('NO_PAGE');
 } else {
 throw Error("Can't get goods: \n" + error.message);
 }
 }
};
const myOtherFunc = async () => {
 try {
 myFunc();
 //... Some code
 } catch (error) {
 if (error.message === 'NO_PAGE') {
 // ...Perform some action;
 }
 console.log(error);
 }
};
asked Dec 14, 2020 at 9:03

1 Answer 1

3

If you prefer to create custom errors, why don't you do so? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types.

Unfortunately you can't catch specific errors in javascript like you're used to in java. So you still have to match something in an if statement.

catch (e) {
 if (e instanceof CustomError)

At least this solution is nicer and less error prone than string matching on error message. Yet, I guess that's also pretty subjective.

answered Dec 16, 2020 at 0:34
1
  • Yes, this seems like the best and the cleanest solution. Thank you @Kleistra Commented Dec 17, 2020 at 9:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.