error-handling - Koa错误处理: is `return` necessary?

标签 error-handling koa

我正在使用koa-routers来处理向第三方api发送电子邮件请求的路由。我是否正确处理错误?我需要退货吗?我应该返回ctx.response吗?我看到一些以func next()结尾的示例。但是,我假设我不需要此功能,因为下游没有其他功能/中间件。

router.post('sendemail', async (ctx) => {
  const emailData = ctx.request.body;
  try {
    await someEmailApi({
      recipient: {
        name: emailData.recipientName,
        address: emailData.recipientEmail,
      },
      sender: {
        name: emailData.senderName,
        address: emailData.senderEmail,
      },
      subject: mail.subject,
      message: mail.message,
    });

    ctx.response.status = 200;
    ctx.response.body = 'OK';
  } catch (err) {

    ctx.response.status = err.status;
    ctx.response.body = err.message';
    ctx.throw(ctx.response.status, ctx.response.body);
  }
});

最佳答案

因此,因为这是一个路由处理程序,所以您通常不调用await next(),因为该路由处理程序无论如何都是“最内部”的中间件,因此next()是无操作的。

如果您使用的是ctx.throw,则无需分别设置状态和正文。

这应该足够了:

ctx.throw(err.status, err.message)

关于error-handling - Koa错误处理: is `return` necessary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805196/

相关文章:

javascript - 无法理解 Node.js 中的错误

authentication - 使用koa和passport进行认证

python - 为什么我有时几乎无法获得有关 Python (Jupyter) 中发生错误的位置的信息?

error-handling - 错误处理 : show error message or not?

r - 规模转化产生的NaN

node.js - 如何在 koa-route 中使用通配符

javascript - 如何在onEnter函数中访问cookie,react.js

node.js - 使用 request-promise 时无法设置 Koajs 的 ctx.status 和 ctx.body

javascript - 为什么 React JS 中的错误边界不起作用

javascript - 即使在添加 catch block 之后,nodejs 中的 "UnhandledPromiseRejectionWarning"