error handling



  1. What kind of errors do you need to confirm to intercept (for example, KOA error or HTTP error)??
  2. What are the error interception methods of this type [HTTP error interception, error judgment in error event and status code]??
  3. What are the methods of JS active throw and intercept error [active throw: throw, reject(), intercept error: try / catch, promise. Catch]??

JS active throw error and intercept error

Active throw error: throw, project.reject callback
Intercept error: try / catch, promise.catch callback

1. Difference between throw and project.reject:
    Essentially different - reject is a callback. Throw is just a synchronous statement. If it is thrown in another asynchronous context, it cannot be caught in the current context.
    new Promise(function (resolve,reject) {
      throw new Error('12');
    }).then(function (data) {
      Console. Log ('reject ', ERR); // execute

    new Promise(function (resolve,reject) {
        Throw new error ('12 '); // an error is reported
    }).then(function (data) {
      Console. Log ('reject ', ERR); // will not execute
2. Try / catch cannot intercept errors in promise, but it can intercept async / await errors:
    In try / catch, when the code in try is executed and no error is thrown, the error will not be intercepted. So try / catch can't intercept errors in promise, but try / catch can intercept errors in promise in async / await. Because the code after await can only be executed after await.
    function f2() {
        try {
            Promise. Reject ('error '). Catch (ERR = >{
                console.log('2', err)
        } catch (e) {

Http / HTTPS error handling

Error event failed to intercept request, error on connection
Statuscode request status code, interception failed

>From node fetch
    let http=require('http');
    let req=http.request(options[,callback])
    req.once('socket', function(socket) {
        reqTimeout = setTimeout(function() {
            reject(new FetchError('network timeout at: ' +          options.url, 'request-timeout'));
        }, options.timeout);
    req.on('error', function(err) {
        reject(new FetchError('request to ' + options.url + ' failed, reason: ' + err.message, 'system', err));
    req.on('response', function(res) {
        //Here you can bind the data & end event to get the data
        if (res.statusCode === 303){
            //You can throw it wrong here

Koa error handling

The koa onion model is helpful for understanding the use of outermost middleware to intercept errors

>Method 1: CTX. Throw (404)
>Method 2: app. Use (async (CTX, next) = >{
        await next()
        //This is the outermost middleware, which will intercept all middleware errors. Modify ctx.body here to control the error information returned to the front end