处理快速异步中间件中的错误

IT技术 javascript node.js express es6-promise
2021-03-09 08:48:58

async在 express 中有一个中间件,因为我想在其中使用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而不是进入我的错误处理中间件,我怎样才能让错误冒出来,并快速处理它?

6个回答

问题是当它拒绝时,它不会转到我的错误中间件,但是如果我删除 async 关键字并将其扔到中间件中,它会这样做。

express 目前不支持 promises,支持可能会在未来发布 express@5.x.x

所以当你传递一个中间件函数时,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不会Promiseasync函数之外捕获拒绝,并且由于express没有.catchPromise中间件返回处理程序添加处理程序,您会得到一个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中间件周围使用了一个包装器next(err)如果Promise被拒绝,它将调用,到达快速错误处理程序并避免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

还有一些包可以使用

还值得一提的是,框架Koa(据说是由最初从事 Express 工作的人构建的)为请求处理程序中的异步操作以及 OP 所要求的那种 Promise 意识和错误处理提供了更多内置便利。
2021-04-21 08:48:58
typescript:export const asyncHandler = (fn: RequestHandler) => (req: Request, res: Response, next: NextFunction) => Promise.resolve(fn(req, res, next)).catch(next)谢谢!
2021-05-05 08:48:58
有关express@5.x.x支持的更多信息expressjs.com/en/guide/error-handling.html我试过了5.0.0-alpha.8,它的工作原理完全符合描述:route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error.
2021-05-09 08:48:58

好吧,我找到了这个 - https://github.com/davidbanham/express-async-errors/,然后需要脚本,你很高兴

const express = require('express');
require('express-async-errors');
这个module还是有用的。如下所述,Express v5 将添加对异步中间件的支持,但截至今天,还没有发布 v5。
2021-05-10 08:48:58

用 asyncHandler 回答是好的和有用的,但是在每个路由中编写这个包装器仍然不舒服。我建议改进它:

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

const methods = [
    'get',
    'post',
    'delete'  // & etc.
]

function toAsyncRouter(router) {
    for (let key in router) {
        if (methods.includes(key)) {
            let method = router[key]
            router[key] = (path, ...callbacks) => method.call(router, path, ...callbacks.map(cb => asyncHandler(cb)))
        }
    }
    return router
}

现在我们可以这样做:

const router = toAsyncRouter(express().Router())
router.get('/', someAsyncController)

等等。

分钟前添加了一个 npm moduleasync-express-decorator

您需要使用 try-catch 并在 catch 部分中传递 next() 参数中的错误,如下所示 -

async create(req, res, next) {

    try {
      const userProp = req.body;
      const user = new User(userProp)

      const response = await user.save()
      const token = await user.createJWSToken()

      res.send({response, token})

    } catch (err){
      next(err)
    }
}

很明显,把这个 express 中间件放在你的 index.js 文件中。

app.use((err, req, res, next) => {
  res.status(422).send({ error: err.message });
});

Express 5 现在处理异步Promise:

https://expressjs.com/en/guide/error-handling.html

从 Express 5 开始,返回 Promise 的路由处理程序和中间件将在它们拒绝或抛出错误时自动调用 next(value)。例如