gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:10:26 28 4
gpt4 key购买 nike

我正在使用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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com