我在express中有一个async中间件,因为我想在其中使用await来清理代码.

const express = require('express');
const app = express();

app.use(async(req, res, next) => {
    await authenticate(req);
    next();
});

app.get('/route', async(req, res) => {
    const result = await request('http://example.com');
    res.end(result);
});

app.use((err, req, res, next) => {

    console.error(err);

    res
        .status(500)
        .end('error');
})

app.listen(8080);

问题是,当它拒绝时,它不会转到我的错误中间件,但如果我删除中间件中的async关键字和throw,它就会转到.

app.get('/route', (req, res, next) => {
    throw new Error('Error');
    res.end(result);
});

所以我得到UnhandledPromiseRejectionWarning,而不是进入我的错误处理中间件,我如何让错误冒泡,并表示处理它?

推荐答案

问题是,当它拒绝时,它不会导致我的错误

express目前不支持promise ,支持可能会出现在express@5.x.x的future 版本中

所以当你传递一个中间件函数时,express将在try/catch块中调用它.

Layer.prototype.handle_request = function handle(req, res, next) {
  var fn = this.handle;

  if (fn.length > 3) {
    // not a standard request handler
    return next();
  }

  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
};

问题是,try/catch不会捕获async函数之外的Promise拒绝,而且由于express不会向中间件返回的Promise添加.catch处理程序,因此会得到UnhandledPromiseRejectionWarning.


简单的方法是在中间件中添加try/catch,然后调用next(err).

app.get('/route', async(req, res, next) => {
    try {
        const result = await request('http://example.com');
        res.end(result);
    } catch(err) {
        next(err);
    }
});

但是如果你有很多async个中间产品,它可能有点重复.

因为我喜欢我的中间件尽可能干净,而且我通常会让错误冒出来,所以我在async个中间件周围使用一个包装器,如果promise 被拒绝,它将调用next(err),到达快速错误处理程序并避免UnhandledPromiseRejectionWarning

const asyncHandler = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandler;

现在你可以这样称呼它:

app.use(asyncHandler(async(req, res, next) => {
    await authenticate(req);
    next();
}));

app.get('/async', asyncHandler(async(req, res) => {
    const result = await request('http://example.com');
    res.end(result);
}));

// Any rejection will go to the error handler

还有一些软件包可以使用

Node.js相关问答推荐

NodeJS中的Vertex AI GoogleAuthError

如何使用聚合管道交换键值对

MongoDB如果文档S的字段小于另一个字段,则将该字段加一

聚合操作不返回任何具有mongoose模式的内容

Webpack:如何避免导出函数的重命名?

Nestjs重写子类dto nodejs中的属性

PEAN auth 应用程序:为什么 Angular 拦截器总是使用BehaviorSubject 返回 null(即初始值),而不是更新后的值?

ResponseError:键空间ks1不存在

如何使用 node 在 koa.js 中发送响应

表达限制资源属于特定用户的优雅方式

node.js 中 pdfkit-tables 中的垂直线

使 pm2 登录到控制台

调用 require 时的 const vs let

带有加密的nodejs中的SALT和HASH密码

编写可维护的事件驱动代码

使用 MongoDB 更新嵌套数组

Express.js:没有这样的文件或目录

chart.js 无法创建图表:无法从给定项目获取上下文

Javascript在try块内设置const变量

使用 Monit 而不是基本的 Upstart 设置有什么好处?