【问题标题】:Express async/await error handling快速异步/等待错误处理
【发布时间】:2018-04-06 08:39:51
【问题描述】:
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 都会被很好地调用,我可以看到“错误发生 > > > ..”的打印。

但是我无法将该错误引导到错误处理程序中间件,我打算在其中发送带有 JSON 错误的 400。

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

【问题讨论】:

  • 使用你的代码,加上一个总是拒绝的假“urlhandler”,我无法复制你描述的问题,res.status(400).json({error: err}); 确实为我调用了

标签: express error-handling promise async-await


【解决方案1】:

抱歉,我无法隔离一段示例代码来轻松演示该错误。我正在使用 mysql,express - 与 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 ****************/

【讨论】:

    猜你喜欢
    • 2017-05-25
    • 2018-07-29
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2022-01-02
    • 2018-07-09
    相关资源
    最近更新 更多