-
Notifications
You must be signed in to change notification settings - Fork 177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A catch-all 404 handler for koa? #158
Comments
Sadly running into the same issue - did you find a solution? |
I handle this in the applications error middleware. import * as createError from "http-errors";
const errorMiddleware = async (ctx, next) => {
try {
await next();
if (ctx.status === 404) {
throw createError(404);
}
} catch (err) {
// handle error
}
}; If any of my handled routes need to return 404, they do so by throwing an error. If |
No need for the extra http-errors package, and also no need to even check the status, not really — the default is 404, so if you add a 404 handler after everything else (except for the app.use(async (ctx, next) => {
ctx.status = 404
ctx.body = 'Not found'
}) |
yesterday, i also meet same problem too! the key is use wrong way of the router/index.js
router/error/index,js
|
Hello!
I'm trying to implement a pretty trivial thing — a catch-all handler that will return 404 when request handler is not found for the request in question, however, I can't find any related examples in the docs and the Internet. What is the best practice for this?
The example below won't work because the
router.all('/(.*)')
will intercept all requests after they were handled. Of course I can do something likecontext.handled = true
and then check for this flag in the catch-all handler, but this will be a boilerplate code that should actually be handled by the router itself. Avoiding a call tonext()
in the request handler will also be a mistake, because it will break the middleware that do request post-processing (e.g. response transformation, etc). If I change the order of handler registration then I will need to set proper status in all the request handlers.I believe the router should provide a special method for handling unhandled requests.
The text was updated successfully, but these errors were encountered: