raphtlw
raphtlw

Reputation: 127

How do I check the type of error in Node JS?

Let's say I have an error:

.catch((err) => {
  res.sendFile(path.join(__dirname, '..', 'public', 'url-error.html'));
  console.log(err.message);
});

How can I check the error type?

e.g.

if (err.message.toLowerCase().contains('invalid operator')) {
  console.log('this is me doing something in this block');
} else {
  console.log('nothing is happening here');
}

P.S. I am catching the error from a library on Node.JS called "ytdl-core".

Upvotes: 1

Views: 7444

Answers (1)

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4915

You can check error code

if (err.code =='ERR_AMBIGUOUS_ARGUMENT') {
  console.log('this is me doing something in this block');
} else {
  console.log('nothing is happening here');
}

https://nodejs.org/dist/latest/docs/api/errors.html#errors_node_js_error_codes

you can use instanceof for type

catch (e) {
    if (e instanceof RangeError) {
      // Output expected RangeError.
      console.log(e);
    } else {
      // Output unexpected Errors.
      console.log(e, false);
    }
  }

Upvotes: 2

Related Questions