koajs / koa

Expressive middleware for node.js using ES2017 async functions
https://koajs.com
MIT License
35.11k stars 3.22k forks source link

[feat] send json type content when call ctx.throw #1754

Closed yunnysunny closed 8 months ago

yunnysunny commented 1 year ago

Describe the feature

Some time we want our server always reponse with json type, even if it throw custom error, for such code:

ctx.throw(403, 'need right access', {
      message: JSON.stringify({code: 1234, msg: 'you dont have right permission', userId: 'xxx'}),
      expose: true
})

But koa reponse all errors with text type, we can not change it.

Checklist

siakc commented 8 months ago

Guess you can put a middle there to catch the error and format the response before Koa. You can pass an object to ctx.throw() as any one of the arguments except first.