function catchException (func, controller) {
return async function (req, res, next) {
req.allParams = Object.assign({}, req.query, req.body, req.params)
LOG.info('req.allParams\n %s', JSON.stringify(req.allParams))
try {
await func.call(controller, req, res)
} catch (e) {
// 非route调用没有req, res, next参数
if (next) {
next(e)
} else {
throw e
}
}
next()
}
}
// 装饰控制器,捕获异步异常等统一由 express 的错误中间件 errorHandle 处理
function exceptionDecorator(controller) {
Object.keys(controller).map(item=>{
if (typeof controller[item] === 'function') {
controller[item] = catchException(controller[item], controller)
}
})
return controller
}
export default exceptionDecorator
对controller进行包装,这样controller里面的异常都会被catchException捕获,然后统一处理。如果不这样处理,异步发生异常时只能在process.on('uncaughtException', fn)和process.on('unhandledRejection', fn)中处理,无法再express框架层处理
export default exceptionDecorator({
/**
* 列表数据
* @return
*/
async list(req, res, next) {
const response = await Project.findAll({
include: [
{
model: Host,
as: 'hosts'
}
],
order: ['name']
})
return res.success(response);
}
})