koajs / onerror

an error handler for koa, hack ctx.onerror
MIT License
140 stars 20 forks source link

how to configure return json format #24

Closed highsung closed 7 years ago

highsung commented 7 years ago

when on error,the default return message is html format, how to configure return json format. Thanks a lot!!

dead-horse commented 7 years ago

default it will use ctx.accept to detect the accept content type, but you can customize by options.accpet. https://github.com/koajs/onerror/blob/master/index.js#L72

marswong commented 6 years ago

simply set options.accepts like:

onerror(app, {
  accepts() {
    if (this.get('accept').includes('json')) return 'json';
    return 'html';
  },
});

and remember to set the Accept header to be application/json for each request, take fetch as an example:

fetch('/xxx', {
  headers: {
    'Accept': 'application/json',
  },
  method: 'xxx',
  ...
})
.then(res => res.json)
.then((res) => {
  // default response format:
  // {
  //   error: 'xxx'
  // }
})