How to handle a 404 in koa 2?

Member

by lily , in category: Javascript , 7 months ago

How to handle a 404 in koa 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 6 months ago

@lily 

To handle a 404 error in Koa 2, you can follow these steps:

  1. Import the NotFound error class from the http-errors library:
1
const { NotFound } = require('http-errors');


  1. 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();
};


  1. Register the handle404 middleware in your Koa application. Make sure it is placed after all other routes and middleware:
1
app.use(handle404);


  1. 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.