app.on("error")
Registers an application-level error handler that receives all uncaught errors from middleware.
Syntax
app.on("error", (err, ctx) => { ... }) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
err | Error | Yes | The error thrown (or rejected) by middleware. |
ctx | Context | No | The Koa context for the request that caused the error. May be `undefined` for errors that occur outside request handling. |
Returns
void — No return value; this is an event listener.
Examples
import Koa from 'koa';
const app = new Koa();
app.on('error', (err, ctx) => {
console.error('Server error:', err.message, {
url: ctx?.url,
status: err.status,
});
// Report to your monitoring service here
});
app.use(async (ctx) => {
if (ctx.path === '/boom') throw new Error('Oops!');
ctx.body = 'ok';
});
app.listen(3000);
Output
Server error: Oops! { url: '/boom', status: undefined }
Notes
Koa silently swallows errors with a `status` of 4xx (client errors) by
default to reduce noise; set `app.silent = false` to log all errors.
Errors with `expose: true` have their message forwarded to the client;
otherwise a generic status text is sent. Always attach an error listener
to avoid crashing on unhandled promise rejections in middleware.