快速异步/等待错误处理 [英] Express async/await error handling

查看:80
本文介绍了快速异步/等待错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class XYZ {

  constructor(app) {

    // app is express object
    this.app = app;

    this.app.route('/api/url')
      .get(this.wrap(this.urlhandler.bind(this)));

    // to send error as json -> this never gets invoked ??
    this.app.use((err, req, res, next) => {
      res.status(400).json({error: err});
      next(err);
    });

  }

  // wraps each async route function to handle rejection and throw errors
  wrap(fn) {
    return function (req, res, next) {
      Promise.resolve(fn(req, res, next)).catch(function (err) {
        console.log('ERROR OCCURED: > > > > > > >  ', err.code);
        next(err)
      });
    }
  }

}

每个快速ASYNC路由都被包装以捕获路由处理函数中的任何拒绝或抛出错误.每当出现此类拒绝或错误时,wrap都会被调用,并且我能够看到"ERROR OCCURED>>> .."的打印信息.

Each express ASYNC route is wrapped to catch any rejection or throw error within route handler functions. Whenever there is such rejection or errors - wrap gets invoked fine and I am able to see print of "ERROR OCCURED > > > .."

但是我无法将该错误传递给错误处理程序中间件,我打算在其中发送400个JSON错误.

However I am unable to channel that error to error handler middleware where I intend to send 400 with JSON error.

如何在上述情况下解决此问题?

How can I fix this in above scenario ??

推荐答案

对不起,我无法隔离示例代码来轻松演示该错误.我正在使用mysql Express-与promises和ES6混合使用.

Sorry, I couldn't isolate a sample piece of code to demonstrate the bug easily. I am using mysql, express - mixed with promises and ES6.

下面是我遇到的一个问题样例及其解决方案.

Below is a sample piece of problem I had and its solution.

问题:我在初始化路由之前添加了错误处理中间件.最后添加错误中间件即可解决!!! (感谢这个stackoverflow问题).

The problem : I was adding error handling middleware before I initialised routes. Adding error middleware at the end solves it!!! (Thanks to this stackoverflow question).

var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser')
var morgan = require('morgan');

//define class
class Sql {

  constructor(pool) {
    this.pool = pool;
  }

  exec(query, params) {
    let _this = this;
    return new Promise(function (resolve, reject) {
      _this.pool.query(query, params, function (error, rows, _fields) {
        if (error) {
          return reject(error);
        }
        return resolve(rows);
      });
    });
  }

}


//define class
class Api {

  constructor(mysqlPool, app) {
    this.mysql = new Sql(mysqlPool)
    this.app = app;

    // this.app.use(this.errMw)
    //console.log('IF ERROR MIDDLEWARE IS ADDED HERE - it was NEVER CALLED');

    /**************** add middleware and routes ****************/
    this.app.get('/', this.asyncWrap(this.root.bind(this)))
    this.app.use(this.errMw) // << USE ERROR MIDDLEWARE HERE
  }

  errMw(err, req, res, next) {

    res.status(400).json({error: err});
    next(err);
  }

  asyncWrap(fn) {
    return (req, res, next) => {
      Promise.resolve(fn(req, res, next))
        .catch((err) => {
          console.log('err > > > > >', err.message);
          next(err);
        });
    }
  }


  run(cbk) {
    this.app.listen(3000)
  }

  async root(req, res) {
    res.json(await this.mysql.exec('select * from customer', []))
  }

}


/**************** START : mysql,express,api -> run ****************/

let args = {}
args['host'] = 'localhost'
args['user'] = 'root'
args['password'] = 'secret'
args['database'] = 'models'

let mysqlPool = mysql.createPool(args)
let app = express()
//app.use(morgan('tiny'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))


let api = new Api(mysqlPool, app);
api.run()


/**************** END : mysql,express,api -> run ****************/

这篇关于快速异步/等待错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆