如何检查Node JS中的错误类型?

时间:2020-01-29 11:35:21

标签: javascript node.js promise

假设我有一个错误:

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

如何检查错误类型?

例如

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。我从Node.JS上名为“ ytdl-core”的库中捕获了错误。

1 个答案:

答案 0 :(得分:1)

您可以检查错误代码

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

您可以使用instanceof进行输入

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