Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set up json for response error messages. #25

Closed
drakejin opened this issue Aug 22, 2017 · 2 comments
Closed

How to set up json for response error messages. #25

drakejin opened this issue Aug 22, 2017 · 2 comments

Comments

@drakejin
Copy link

drakejin commented Aug 22, 2017

code

const onerror = require('koa-onerror')
const app = new Koa()

onerror(app, {
  accepts: 'json',
})

.... occurred an error.

Your code print out this message

(node:25492) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: options.accepts.call is not a function
(node:25492) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

  • How to set up JSON for response error messages when my node program has an error?
  • I think your document add some code and comment for this situation. If you reply to my issue, I will send P.R.
  • I saw this link( https://github.com/koajs/onerror/blob/master/index.js#L38), so what should I do? What do you want to me? please, more tell me some guide
@dead-horse
Copy link
Member

accepts must be a function like:

accepts() {
  if (this.path.endsWith('.json')) return 'json';
  return 'html';
}

@marswong
Copy link

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'
  // }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants