1
votes

I'm using Express-validation to validate request fields. everything is working as it supposed to be, except for the response error code.

I have the following code:

//
// ValidationLeaner.js
const Joi = require('joi');

module.exports = {
  body: {
    name: Joi.string().min(3).max(20).required(),
    classifierId: Joi.number().integer().positive().required()
  }
}

//Route.js
const { Router } = require('express')
const Validate = require('express-validation')
const ValidationLearner = require('./ValidationLeaner')

const router = Router()

router.route('/').post(Validate(ValidationLearner), ...someFunction)

module.exports = router

When sending a POST request with body: {name: "Leaner01", classifierId: false}. I receive the following response, which is correct:

{
  "status": 400,
  "statusText": "Bad Request",
  "errors": [
     {
       "field": [ "classifierId" ],
       "location": "body",
       "messages": [ "\"classifierId\" must be a number" ],
       "types": [ "number.base" ]
      }
  ]
}

Unfortunately the response code is 500 Internal Server Error and not 400 as pointed in the response body.

How can we make Express-validation send the same response code stated in the body (status: 400)?

2

2 Answers

1
votes

I believe that changing this line

const { ValidationLearner } = require('./ValidationLeaner')

into

const ValidationLearner = require('./ValidationLeaner')

will change the result. Because in the first case ValidationLearner is undefined since ValidationLearner.js (is it ValidationLeaner.js or ValidationLearner.js) exports an object that has a first-level property named body and not ValidationLearner.

1
votes

Do you have an error handle in your main file (index, app or server.js) , because in the express-validation docs it is required.

Can you add this error handler (or edit it if you already have) to your main file (index, app or server.js) and try again?

const Validate = require("express-validation");

app.use(function(err, req, res, next) {
  // specific for validation errors
  if (err instanceof Validate.ValidationError)
    return res.status(err.status).json(err);

  // other type of errors, it *might* also be a Runtime Error
  return res.status(500).send(err.stack);
});