Handling specific errors in JavaScript (think exceptions)

前端 未结 6 1755
醉梦人生
醉梦人生 2020-12-02 11:28

How would you implement different types of errors, so you\'d be able to catch specific ones and let others bubble up..?

One way to achieve this is to modify the

6条回答
  •  渐次进展
    2020-12-02 12:21

    try-catch-finally.js

    Using try-catch-finally.js, you can call the _try function with an anonymous callback, which it will call, and you can chain .catch calls to catch specific errors, and a .finally call to execute either way.

    Example

    _try(function () {
        throw 'My error';
    })
    .catch(Error, function (e) {
        console.log('Caught Error: ' + e);
    })
    .catch(String, function (e) {
        console.log('Caught String: ' + e);
    })
    .catch(function (e) {
        console.log('Caught other: ' + e);
    })
    .finally(function () {
        console.log('Error was caught explicitly');
    });
    

    Example with modern arrow functions and template literals

    _try(() => {
      throw 'My error';
    }).catch(Error, e => {
      console.log(`Caught Error: ${e}`);
    }).catch(String, e => {
      console.log(`Caught String: ${e}`);
    }).catch(e => {
      console.log(`Caught other: ${e}`);
    }).finally(() => {
      console.log('Error was caught explicitly');
    });
    

提交回复
热议问题