[英]Express async/await error handling
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)
});
}
}
} }
Each express ASYNC route is wrapped to catch any rejection or throw error within route handler functions. 每个快速ASYNC路由都经过包装,以捕获路由处理程序函数中的任何拒绝或抛出错误。 Whenever there is such rejection or errors - wrap gets invoked fine and I am able to see print of "ERROR OCCURED > > > .." 每当出现此类拒绝或错误时,wrap都会被调用,并且我能够看到“ ERROR OCCURED>>> ..”的打印。
However I am unable to channel that error to error handler middleware where I intend to send 400 with JSON error. 但是,我无法将该错误引导到错误处理程序中间件,在该处我打算发送400个JSON错误。
How can I fix this in above scenario ?? 如何在上述情况下解决此问题?
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. 我正在使用mysql Express-与promise和ES6混合使用。
Below is a sample piece of problem I had and its solution. 以下是我遇到的一个问题样本及其解决方案。
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 ). ( 由于这个stackoverflow问题 )。
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 ****************/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.