有没有办法将 await/async try/catch 块包装到每个函数中? [英] Is there a way to wrap an await/async try/catch block to every function?

查看:38
本文介绍了有没有办法将 await/async try/catch 块包装到每个函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用 express.js 并考虑在节点 7 中使用 async/await.有没有办法我仍然可以捕获错误但摆脱 try/catch 块?也许是函数包装器?我不确定这将如何实际执行函数的代码并调用 next(err).

So i'm using express.js and looking into using async/await with node 7. Is there a way that I can still catch errors but get rid of the try/catch block? Perhaps a function wrapper? I'm not sure how this would actually execute the function's code and also call next(err).

exports.index = async function(req, res, next) {
  try {
    let user = await User.findOne().exec();

    res.status(200).json(user);
  } catch(err) {
    next(err);
  }
}

像这样的东西......?

Something like this...?

function example() {
   // Implements try/catch block and then handles error.
}

exports.index = async example(req, res, next) {
  let user = await User.findOne().exec();
  res.status(200).json(user);
}

与此更相似的内容:

var wrapper = function(f) {
    return function() {
        try {
            f.apply(this, arguments);
        } catch(e) {
            customErrorHandler(e)
        }
    }
}

这会以某种方式处理 try/catch 块,但不起作用:

This would somehow handle the try/catch block but doesn't work:

exports.index = wrapper(async example(req, res, next) {
  let user = await User.findOne().exec();
  res.status(200).json(user);
});

有吗一种向 Javascript 中的每个函数添加 try-catch 的方法? 对于非异步示例.

推荐答案

是的,您也可以轻松地为异步函数编写这样的包装器 - 只需使用 async/await:

Yes, you can easily write such a wrapper for asynchronous functions as well - just use async/await:

function wrapper(f) {
    return async function() {
//         ^^^^^
        try {
            return await f.apply(this, arguments);
//                 ^^^^^
        } catch(e) {
            customErrorHandler(e)
        }
    }
}

或者你直接使用promise,就像这个例子中更适合表达(尤其是参数数量):

Or you use promises directly, like in this example that is more tailored to express (especially with the number of parameters):

function promiseWrapper(fn) {
    return (req, res, next) => {
         fn(req, res).catch(next);
    };
}

这篇关于有没有办法将 await/async try/catch 块包装到每个函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆