Koa: On error [ctx.throw()] the response is forced to text/plain

Created on 21 Jun 2016  路  10Comments  路  Source: koajs/koa

Hey guys,

I noticed that u force plain text on error response. https://github.com/koajs/koa/blob/master/lib/context.js#L125

Is this on purpose? Also how to expose error properties?

question

Most helpful comment

this.throw(400, JSON.stringify({ error: 'Encountered an error' })?

All 10 comments

You should probably be implementing a custom error handler.

Yes, I think the reason behind it is to encourage you to "fix it" yourself with an error handling middleware that makes sense to you.

For Koa 2:

app.use((ctx, next) => {
  return next().catch(err => {
    ctx.status = 400;
    ctx.body = {
      message: 'Oh noes!',
      error: err
     };
   });
});

That catches promise rejections. If using Koa 2 with async-await (you should!):

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = 400;
    ctx.body = {
      message: 'Oh noes!',
      error: err
    };
  }
});

@jeffijoe No need to worry about sync exceptions, koa-compose turns them into async exceptions.

@PlasmaPower given that you are using koa-compose at all times. ;)

@jeffijoe I'm not sure I understand, koa internally uses koa-compose to chain together the middleware.

@PlasmaPower oh, I didn't realize that, my bad :)

@PlasmaPower @jeffijoe If I throw an explicitly it goes through my custom error handler. Unfortunately ctx.throw() is not going through my custom error handler.

Will have to see if I've done something wrong.

@pasupulaphani I don't see why it shouldn't be. Are you sure your error handler isn't crashing itself when it receives an httpError?

this.throw(400, JSON.stringify({ error: 'Encountered an error' })?

@pasupulaphani please ensure your error handler is in front of all other middlewares.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sibelius picture sibelius  路  3Comments

usernameisalreadytaken2014 picture usernameisalreadytaken2014  路  4Comments

TheRav3n picture TheRav3n  路  3Comments

ilkkao picture ilkkao  路  4Comments

wlingke picture wlingke  路  3Comments