krakenjs / swaggerize-routes

Swagger document driven route builder.
Other
58 stars 57 forks source link

Example how to use validators #60

Closed marcofranssen closed 8 years ago

marcofranssen commented 8 years ago

Hi,

How can I use the validators in my express app to return a specific response when validation fails? I would love to see a small example on how to use the validators.

What I'm currently facing is that some of my unittests return a 400 error caused by the validator, but it is not returning any information neither the correct content-type.

Is there a way to influence the response given by validation errors?

Anyone able to help me out?

marcofranssen commented 8 years ago

I found a solution that works for me, so here it goes as reference for anyone looking for this information in the future. Bsically just include an errorhandler middleware after you configured swaggerize express. Now I'm able to format the response of any unhandled error, even those not coming from swagger validation.

const exists = require('api/models/utils').exists;
const responses = require('api/models/responses');

// swaggerize-express setup

app.use(function (err, req, res, next) {
         if (exists(err) && err.name === 'ValidationError') {
             let respond = responses[err.status];
             if (exists(respond)) {
                 return respond(res, err);
             }
         }
    next();
});