快速异步/等待错误处理

时间:2017-10-25 09:54:50

标签: express error-handling promise async-await

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路由都被包装以捕获路由处理函数中的任何拒绝或抛出错误。每当有这样的拒绝或错误时 - 包裹被调用很好,我能够看到“ERROR OCCURED>>> ..”的打印。

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

如何解决上述情况?

1 个答案:

答案 0 :(得分:0)

抱歉,我无法隔离示例代码以轻松演示错误。我正在使用mysql,表达 - 与promises和ES6混合。

以下是我遇到的一个问题及其解决方案。

问题:我在初始化路由之前添加了错误处理中间件。最后添加错误中间件解决了它! (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 ****************/