To register custom error handlers in Koa, we simply need to define middleware with a try... catch statement to capture the errors, then send responses back to the client. This should be done at the top of the stack.
We can define error handlers based on various requirements to handle different types of errors for different types of clients. These error handlers can be used independently or combined, depending on the needs of the application. Let's define a set of error handlers and register them in our application:
const jsonErrorHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
const isJson = ctx.get('Accept') === 'application/json';
if (isJson) {
ctx.body = {
error: 'An error just occurred'
}
} else {
throw err;
}
}
}
app.use(jsonErrorHandler);
The first error handler defined is for catching errors on Ajax requests or requests that only accept JSON responses.
Next, we can define a catch-all error handler. This can be substituted with an error page in a real-life application:
const errorHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = err.expose ? err.message : 'An error occurred!';
}
}
app.use(errorHandler);
Putting both error handlers together, they will look like the code block below:
// define generic error handler
const errorHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = err.expose ? err.message : 'An error occurred!';
}
}
// register generic error handler middleware
app.use(errorHandler);
// define json request error handler
const jsonErrorHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
const isJson = ctx.get('Accept') === 'application/json';
if (isJson) {
ctx.status = err.status || 500;
ctx.body = {
error: `An error just occurred`
}
} else {
throw err;
}
}
}
// register json error handler middleware
app.use(jsonErrorHandler);
Note: We register the generic handler first, as it will be the last middleware to be executed as the middleware stack unwinds.