4

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);
  }
};
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.

1
  • Yes, this seems like the best and the cleanest solution. Thank you @Kleistra – dani.luis Dec 17 '20 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.