nodejs 装饰器方式处理controller异常

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);
    }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,616评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,279评论 1 3
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,121评论 2 7