I'm using koa-routers to handle a route for making a send email request to a third-party api. Am I error handling correctly? Do I need to return anything? Should I return ctx.response
? I see some examples that ends the func with await next(). However, I'm assuming I don't need this as there is no other func/middleware to downstream to.
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);
}
});
So because this is a route handler, you usually don't call await next()
because the route handler is the "inner-most" middleware anyway, so next()
is a no-op.
If you are using ctx.throw
you don't need to set the status and body separately.
This should be enough:
ctx.throw(err.status, err.message)