Search code examples
error-handlingkoa

errorFormatter koa-async-validator


I am trying to apply errorFormatter in ``koa-async-validator` (https://www.npmjs.com/package/koa-async-validator):

I do (as in their example):

app.use(koaValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

But how should I call that errorFormatter?

The below does not seem to format errors:

let errors = await ctx.validationErrors().errorFormatter()

Or

errors.errorFormatter()

Solution

  • You don't have to call directly it.

    you have to call

    let errors = await ctx.validationErrors()
    

    or

    let errors = await ctx.validationErrors(true)
    

    where errors will have the format you defined in errorFormatter for each error.