Asynchronous programming error handling

Foreword

In the project, the application of the basic Promise to solve the asynchronous programming, e.g. ajax request. In this scenario, there is a very common requirement is to capture an exception request. This article as a starting point, combing summarized exception error classification.

A, Promise error handling

Common misclassification
  1. Coding errors
    such that the development process, coding is wrong.
let promise = new Promise(function(resolve, reject) {
    const a = 0;
    a = 10;
});

promise.catch(function(error) {
    console.log('这里打印的错误:',error.message);
});
  1. Initiative to throw an error
    business scenarios: http status value of the request is the result of 4xx, 5xx, or code value represents the business is wrong, we need to throw an exception.

In the internal structure comprising an implicit function try-catch, so the interior of errors will be caught and passed rejection process.

let promise = new Promise(function(resolve, reject) {
    throw new Error("出错啦~");
});

promise.catch(function(error) {
    console.log('这里打印的错误:',error.message);
});

Equivalent to the following:

let promise = new Promise(function(resolve, reject) {
    try {
      throw new Error("出错啦~");
    } catch (err) {
      reject(err);
    }
});

promise.catch(function(error) {
    console.log('这里打印的错误:',error.message);
});
  1. 使用 reject 抛出异常比 throw 更好
    Throw thrown by mistake can be catch in sync task, but if asynchrony, promise will not be captured.

Run the following examples can be found, you can not capture the error.

let promise = new Promise(function(resolve, reject) {
    setTimeout(() => {
        throw new Error("出错啦~");
    },20)
});

promise.catch(function(error) {
    console.log('这里打印的错误:',error.message);     // 无法捕获到错误
});

The reason: While there's constructor promise implicit try-catch, but because setTimeout () is an asynchronous task, so the timing of it than try-catch callback function that executes the catch statement late lead did not regect ( ) go wrong, resulting in abnormal promise can not be caught by catch.

let promise = new Promise(function(resolve, reject) {
      try {
        setTimeout(() => { // 回调函数执行的晚
          throw new Error("出错啦~");
        },20)
      } catch (err) {
        reject(err);  // 没有执行
      }
});

So here we are recommended reject alternative throw. As follows:

let promise = new Promise(function(resolve, reject) {
    setTimeout(() => {
        reject(new Error("出错啦~"));
    },20)
});
  1. The resolve () throws back an error will be ignored
let promise = new Promise(function(resolve, reject) {
    setTimeout(() => {
    resolve()
        reject(new Error("出错啦~"));
    },20)
});
promise.catch(function(error) {
    console.log('这里打印的错误:',error.message);     // 无法捕获到错误
});
  1. promise chain anomalies

Run the following example:

let promise = Promise.resolve();
promise.then(() => {
 return Promise.reject("first");
}).then(() => {
  console.log("two 没执行");
  return Promise.reject('two');
}).catch((err) => {
  console.log(err); // first
}).then(() => {
  console.log("catch 返回的是一个 promise 对象"); // catch 返回的是一个 promise 对象
   return Promise.reject('three');
}).catch((err) => {
  console.log(err); // three
})
  • After reject throw an error, then no subsequent execution, errors are captured to a recent catch
  • catch a promise to return
  1. The reject nested promise

From this point [translation] depth Promise Error Handling

let p2 = new Promise(function(resolve, reject) {
  reject('我是内部的 promise 抛出的错误')
})
let p1 = new Promise(function(resolve, reject) {
  resolve(p2)
})
p1.catch(err => {
   console.log(err)
})

Two, Genertor error handling

  1. Internal function abnormalities
    in external capture the error by try-catch statement.
function *gen() {
  const a = 1;
  yield a = 2; // 故意写错
}
const task = gen();
try {
  task.next();
} catch (e) {
  console.log('捕获到错误了:',e);
}
  1. By generator throw()throws an exception

Inside a generator function, capture the error through try-catch.

  • When the exception is caught, Generator function continues down until the next operation and outputs a yield value after the yield of the expression.
function *gen() {
  try {
    yield console.log(1);
  } catch (e) {
    console.log(e);
  }
  yield console.log(2);
}
const task = gen();
task.next();
task.throw("抛出了异常")

Note the try-catch position, that position should be cast wrong and try-catch broadly in line, otherwise still not be captured.

1567373-bc797f5ec7ab5fd9.png
image.png

reference

Promise.catch developer.mozilla ()
"Understanding ECMAScript 6" (Simplified Chinese) Promise and asynchronous programming
"Understanding ECMAScript 6" (Simplified Chinese) iterators and generators

Recommended Reading

Evolution Callback Promise Generator Async-Await and exception handling

Reproduced in: https: //www.jianshu.com/p/96453478d9f4

Guess you like

Origin blog.csdn.net/weixin_33762130/article/details/91283881