What error handling is built into the app?
What error handling is built into the app?
About koajs/koa · 2 messages · last activity 7/12/2026
Koa has built-in error handling through the onerror method in the context object. Here's what's built into the app:
Error Handling Mechanism
Context-level error handling is implemented in [lib/context.js:L106-L163]. When an error occurs, the onerror method:
-
Validates the error: Converts non-Error objects to Error instances. If a non-error value is thrown, it's stringified using
util.format('non-error thrown: %j', err)[lib/context.js:L118-L119] -
Delegates to app-level handler: Emits the error to the app via
this.app.emit('error', err, this)[lib/context.js:L125], allowing you to register error listeners at the application level. -
Clears headers: If headers haven't been sent yet, it removes all previously set headers and allows the error response to set new ones [lib/context.js:L140-L146]
-
Sets default status code: Uses
err.statusorerr.statusCodeif valid (must be a number with a valid HTTP status message). Defaults to 500 if missing or invalid [lib/context.js:L152-L153] -
Responds with error message: Responds with either the error message (if
err.exposeis true) or a generic HTTP status message (e.g., "Internal Server Error") [lib/context.js:L156-L161]
App-level Error Events
The app emits 'error' events that you can listen to. Tests show this in action—for example, [tests/application/currentContext.test.js:L59-L71] shows an error handler receiving both the error and context.
Async LocalStorage Support
Koa can optionally track context during error handling via asyncLocalStorage. When enabled with new Koa({ asyncLocalStorage: true }), app.currentContext returns the context even in error handlers [tests/application/currentContext.test.js:L54-L71].
FOLLOW_UPS:
- How does middleware handle errors with the next() function?
- Can you customize error responses beyond status and message?
- What happens if headers are already sent when an error occurs?
Want to ask your own question?
Open chat for koajs/koaPublic Q&A. Generated by RepoPilot from the actual source of koajs/koa. AI answers can be incomplete or stale — verify before relying on them.