W
W
Wasya UK2020-01-21 17:33:59
Node.js
Wasya UK, 2020-01-21 17:33:59

Error handling in Koa.js?

How do you handle errors in Koa.js? I'm just learning development, and I don't really understand how it's done correctly, but it seems to me that there should be a universal variant. There are a lot of articles, but the ones that I found boil down to the option below:
I do this, but I'm not sure if it's right to do it...

const errorhandler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.statusCode || err.status || 500;
    ctx.body = {code: err.statusCode, message: err.message};
    ctx.app.emit('error', err, ctx);
  }
};
app.use(errorhandler);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question