How to write error back to browser in koa?

by giovanny.lueilwitz , in category: Javascript , 5 months ago

How to write error back to browser in koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 5 months ago

@giovanny.lueilwitz 

To write an error back to the browser in Koa, you can use the context.throw method. Here's an example of how to do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    // Set the status code and error message
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };

    // Optionally, you can log the error
    console.error(err);
  }
});

app.use(async (ctx) => {
  // Throw an Error object with a status code and message
  ctx.throw(404, 'Resource Not Found');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});


In this example, the first middleware wraps subsequent middleware and handlers in a try-catch block. If an error is caught, it sets the response status code and message based on the error object. The error is then logged to the console.


In the second middleware, a 404 error is thrown using ctx.throw. This will be caught by the first middleware, and the error details will be sent back to the browser.


You can customize the error status code, message, and additional properties as needed.