Koa.js: Centralized error handling Koa.js: Centralized error handling mongoose mongoose

Koa.js: Centralized error handling


There is a section on error handling in the Koa wiki: https://github.com/koajs/koa/wiki/Error-Handling

They recommend using an error handler middleware as one of the first middlewares in your application so that any errors thrown downstream will bubble up to it.

Their example from the wiki:

app.use(async (ctx, next) => {  try {    await next();  } catch (err) {    ctx.status = err.status || 500;    ctx.body = err.message;    ctx.app.emit('error', err, ctx);  }});app.on('error', (err, ctx) => {  /* centralized error handling:   *   console.log error   *   write error to log file   *   save error and request information to database if ctx.request match condition   *   ...  */});


The following code will ensure that any unhandled promise error or any uncaught error, if not handled locally, will get its treatment:

app.use(async (ctx, next) => {  try {    await next();  } catch (err) {    ctx.status = err.status || 500;    ctx.body = err.message;    ctx.app.emit('error', err, ctx);  }});...someUnhandledError();...process.on("unhandledRejection", (reason: string) => {  // I just caught an unhandled promise rejection,  // let's throw it here so my central error handler can catch it  throw new AppError(reason, 500);});process.on('uncaughtException', (error: Error) => {  // I just received an error that was never handled, time to handle it  // by throwing it so my error handling middleware can catch it  throw new AppError("Error", 500)});app.on('error', (err, ctx) => {  // centralized error handling:  // console.log(error)  // write error to log file});app.listen(3000);

Note: Here, the AppError class being used is a custom class that extends the Error class.