@lily
To handle a 404 error in Koa 2, you can follow these steps:
- Import the NotFound error class from the http-errors library:
1
|
const { NotFound } = require('http-errors');
|
- Create a middleware function that throws a NotFound error. This function should be placed after all other routes and middleware, so that if none of them match the requested URL, this middleware will be triggered:
1
2
3
4
|
const handle404 = async (ctx, next) => {
throw new NotFound(); // Throws a 404 error
await next();
};
|
- Register the handle404 middleware in your Koa application. Make sure it is placed after all other routes and middleware:
- Finally, create an error handling middleware that checks for the NotFound error and sends an appropriate response back to the client:
1
2
3
4
5
6
7
8
9
10
11
12
|
app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
if (error instanceof NotFound) {
ctx.status = 404;
ctx.body = 'Not Found';
} else {
throw error; // re-throw any other errors for default error handling
}
}
});
|
Now, when a route is requested that doesn't match any of the defined routes, the handle404
middleware will throw a NotFound
error. The error handling middleware will then catch the error, set the response status to 404, and send the 'Not Found' message back to the client.