Koa provides a helper method for easily throwing errors with appropriate HTTP status codes. It uses http-errors for error creation. The ctx.throw() method throws an error with a .status property, which is 500 (Internal Server Error) by default. This error with the status property enables Koa to respond properly when different errors occur. The method has the signature, ctx.throw([status], [error], [properties]). The following different usages are permitted:
ctx.throw(401);
ctx.throw(401, 'Access denied to the resource');
ctx.throw(401, 'Access denied to the resource', { user });
Throwing ctx.throw(401, 'Access denied to the resource'), for example, is shorthand for the following:
const err = new Error('Access denied to the resource');
err.status = 401;
err.expose = true;
throw err;
It is important to note that these errors are OK for sending to the user, meaning err.expose is set to true. This is usually not the case, especially for 50x errors, where we would not want sensitive details about our app failures to be shown to users, who could possibly be malicious.
The .throw() method also optionally take a properties object that is merged into the error as is. This can be used for passing extra information, which is reported to the requested upstream and can also be used for creating better error messages:
app.use(async ctx => {
ctx.throw(401, 'Access denied to the resource', { user });
});
The error thrown in the preceding code block can be used for creating better error messages, as seen in the following example:
app.use(async (ctx, next) => {
try {
await next();
} catch(err) {
ctx.body = err.message;
if (err.status === 401) {
const { email } = err.user;
ctx.body = `user with email ${email} does not have access to
resource`;
}
}
});
Here is a list of the supported status codes:
- 400: Bad Request
- 401: Unauthorized
- 402: Payment Required
- 403: Forbidden
- 404: Not Found
- 405: Method Not Allowed
- 406: Not Acceptable
- 407: Proxy Authentication Required
- 408: Request Timeout
- 409: Conflict
- 410: Gone
- 411: Length Required
- 412: Precondition Failed
- 413: Payload Too Large
- 414: URI Too Long
- 415: Unsupported Media Type
- 416: Range Not Satisfiable
- 417: Expectation Failed
- 418: I'm A Teapot
- 421: Misdirected Request
- 422: UnprocessableEntity
- 423: Locked
- 424: FailedDependency
- 425: Unordered Collection
- 426: Upgrade Required
- 428: Precondition Required
- 429: Too Many Requests
- 431: Request Header Fields Too Large
- 451: Unavailable For Legal Reasons
- 500: Internal Server Error
- 501: Not Implemented
- 502: Bad Gateway
- 503: Service Unavailable
- 504: Gateway Timeout
- 505: HTTP Version Not Supported
- 506: Variant Also Negotiates
- 507: Insufficient Storage
- 508: Loop Detected
- 509: Bandwidth Limit Exceeded
- 510: Not Extended
- 511: Network Authentication Required
Note that 5xx status code errors do not expose the error message to the response body in Koa.