【问题标题】:Async/await mvc express problems handling errors with .catch()Async/await mvc express 使用 .catch() 处理错误的问题
【发布时间】:2021-04-28 15:29:21
【问题描述】:

我正在尝试使用 express 中间件处理错误,这些行我有以下错误

user.js 控制器

app.post('/create', async (req, res, next) => {
  const data = await User.create(req.body)
    .catch((err) => next(err));
  res.status(201).json({ ok: true, ...data });
});

user.js 模型

UserSchema.statics.create = async function createUser(data) {
  delete data.role;
  const user = await new this(data).save();
  return { token: user.newToken(), user };
};

app.js

app.use((err, req, res, next) => {
  res.status(err.code || 400);
  res.json({ ok: false, err: err.message });
});

错误

(node:3304) UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头 ...

(node:3304) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝编号:9)

(node:3304) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

user.js 控制器中使用 try/catch 进行验证后,我没有任何错误,但在 express 文档中不建议使用 try/catch。

app.post('/create', async (req, res, next) => {
  try {
    const data = await User.create(req.body)
    res.status(201).json({ ok: true, ...data });
  } catch (err) {
    next(err);
  }
});

有什么想法吗?

【问题讨论】:

    标签: node.js express mongoose async-await try-catch


    【解决方案1】:

    您可以使用awaitthen/catch

    app.post('/create', async (req, res, next) => {
      User.create(req.body)
        .then(data => {
           res.status(201).json({ ok: true, ...data });
         })
        .catch((err) => next(err));
    });
    

    【讨论】:

      猜你喜欢
      • 2023-01-05
      • 2018-09-03
      • 1970-01-01
      • 2020-02-20
      • 2021-10-24
      • 2021-10-30
      • 2021-12-31
      • 2016-08-04
      • 2020-11-19
      相关资源
      最近更新 更多