ctx.throw()
Throws an HTTP error that Koa catches and converts to an appropriate HTTP response, stopping middleware execution.
Syntax
ctx.throw([status], [message], [properties]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
status | number | No | HTTP status code. Defaults to `500`. Common values: `400`, `401`, `403`, `404`, `422`, `500`. |
message | string | No | Human-readable error message. Exposed to the client when `expose` is true (automatic for 4xx errors). |
properties | object | No | Additional properties merged onto the error object (e.g. `{ expose: true, headers: { ... } }`). |
Returns
never — Always throws; never returns.
Throws
HttpError— Always — this function's sole purpose is to throw.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
const user = await findUser(ctx.query.id);
if (!user) ctx.throw(404, 'User not found');
ctx.body = user;
});
app.listen(3000);
Output
HTTP/1.1 404 Not Found
{"message":"User not found"}
// Throw with extra properties
ctx.throw(403, 'Insufficient permissions', {
expose: true,
headers: { 'WWW-Authenticate': 'Bearer' },
});
Output
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer
Notes
Uses the [http-errors](https://github.com/jshttp/http-errors) package
internally. The error's `status` property controls the response status
code. 4xx errors have `expose: true` by default (message is sent to the
client); 5xx errors have `expose: false` (generic message sent). Use
`ctx.assert()` for guard-style checks.