koajs / bodyparser

Koa body parsing middleware
MIT License
1.31k stars 116 forks source link

how to detect invalid JSON and response some helpful message? #18

Closed eisneim closed 9 years ago

eisneim commented 9 years ago

some guy may try to post some wired string and set header to be json, i can caught the error but don't know how to response a custom message that tell them," dude, your json is invalid !"

i tried something like this:

app.use(function*(next){
    if(/get|delete|head/i.test(this.method)) return yield next;
    if( /json/i.test( this.get('Content-Type') ) ){
      try{
        require('co-body').json(this)()....... blah blah blah.....
      }catch(e){

      }
    }

    yield bodyParser({
      formLimit: '200kb',
      jsonLimit: '1mb',
    }).call(this,next)
  });

i looked the source code, there is no error handling;

dead-horse commented 9 years ago

https://github.com/cojs/co-body/blob/master/lib/json.js#L36

error is thrown here, you can add this in your custom error handler:

try {
   yield bodyParser({
      formLimit: '200kb',
      jsonLimit: '1mb',
    }).call(this,next)
} catch (err) {}
eisneim commented 9 years ago

stupid me!! just after i post the issue , i realized i can do it in that way! thanks anyway

eisneim commented 9 years ago

this method will also have a problem, it will caught not only the JSON parse error but all the nested middleware's error and router's error , which means, app.on('error') will become useless.

how to make this better?

dead-horse commented 9 years ago

maybe we can add options.onerror for koa-bodyparser to support custom error handler?

eisneim commented 9 years ago

it would be great ! my current solution is: add global error handler and check error type

if((err instanceof SyntaxError) && err.body ){
    error = {
        msg:'JSON对象语法错误,请检查',
        detail: err.toString(),
    }
}
dead-horse commented 9 years ago

https://github.com/koajs/bodyparser/commit/194181298fe3bffce6b5fcf3cfebc35b8cda6c89

dead-horse commented 9 years ago

koa-bodyparser@1.6.0

eisneim commented 9 years ago

pretty efficient!