Express异步异常处理(Async Error Handler)

Express处理异步异常

Express可以很好的处理同步的异常,即一旦有同步异常 throw err,则自动转化为:

js 复制代码
next(err)

以等待后续处理。

但是异步的异常就没办法自动了。如果没有特殊处理的话,它就直接报错了。

Express官方也提出解决方法了,就是要手动 next(err) 一下:

You must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example:

javascript 复制代码
app.get('/', (req, res, next) => {
  setTimeout(() => {
    try {
      throw new Error('BROKEN')
    } catch (err) {
      next(err)
    }
  }, 100)
})

The above example uses a try...catch block to catch errors in the asynchronous code and pass them to Express. If the try...catch block were omitted, Express would not catch the error since it is not part of the synchronous handler code.

然而 try ... catch ... 并非唯一可以手动 next(err) 的途径,Promisecatch 也行。当然,Express官方也在下面提供了这一方法

Use promises to avoid the overhead of the try...catch block or when using functions that return promises. For example:

javascript 复制代码
app.get('/', (req, res, next) => {
  Promise.resolve().then(() => {
    throw new Error('BROKEN')
  }).catch(next) // Errors will be passed to Express.
})

Since promises automatically catch both synchronous errors and rejected promises, you can simply provide next as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument.

理论可行,那么就开始封装吧

封装

StackOverflow 中,Marcos Casagrande 的帖子 "Handling errors in express async middleware" (Jul 2018) 完美封装了这个异步异常处理器。感兴趣的朋友可以点击链接去看看。

以下是我对这个封装的理解:

首先 Mr.Casagrande 的代码如下:

js 复制代码
const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandler;

如果 fn 正常运行了,那么 catch 会 catch 个寂寞,从而跳过 catch 里面的 next

如果 fn 运行途中有报错,那么 catch 拿到这个 err,会调用回调函数 next 并将 err 作为第一个参数传入。而这个,正好是 Express 处理异常所需要的。

使用

使用的时候就直接把那个有可能有异步异常的异步函数给套起来就行了:

js 复制代码
app.get(
  '/your/api/path',
  asyncHandler(async (req, res, next) => {
    ... // 业务代码
  })
);

引用 References

相关推荐
小皮虾16 分钟前
搞全栈还在纠结 POST、GET、RESTful?试试这个,像调用本地函数一样写接口
前端·node.js·全栈
程序员爱钓鱼37 分钟前
Node.js 编程实战:路由与中间件
前端·后端·node.js
程序员爱钓鱼40 分钟前
Node.js 编程实战:Express 基础
前端·后端·node.js
亮子AI1 小时前
【node.js】node.js 两种模块规范 CommonJS 和 ESM 如何选择?
node.js
孟祥_成都1 小时前
nest.js / hono.js 一起学!日志功能/统一返回格式/错误处理
前端·node.js
亮子AI2 小时前
【node.js MySQL】node.js 如何连接 MySQL?
数据库·mysql·node.js
亮子AI3 小时前
【node.js】如何使用 node.js 来制作命令行应用?
node.js
大布布将军3 小时前
⚡️编排的艺术:BFF 的核心职能——数据聚合与 HTTP 请求
前端·网络·网络协议·程序人生·http·node.js·改行学it
大布布将军1 天前
⚡️ 后端工程师的护甲:TypeScript 进阶与数据建模
前端·javascript·程序人生·typescript·前端框架·node.js·改行学it
程序员小易1 天前
前端轮子(1)--前端部署后-判断页面是否为最新
前端·vue.js·node.js