Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Express-Validator "validationResult" returns [object Object]

I'm modifying the Error handling of the Express-Validator middleware to go through my custom Error Handling middleware but the message of the validationResult resolves to [object Object].

Express-Validator error handling

const expressValidationError = (req, res, next) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {
    const err = new Error(errors.array());
    err.status = 400;
    next(err);
  } else {
    next();
  }
};

Express Error Handling middleware

app.use((err, req, res, next) => {
  const status = err.status || 500;
  res.status(status).json({
    error: {
      status: status,
      message: err.message || "Internal Server Error",
    },
  });
});

This is the result of the error object which is returned from validationResult:

Result {
  formatter: [Function: formatter],
  errors: [
    {
      value: 'b',
      msg: 'Username Must be Between 5 to 255 Characters Long!',
      param: 'username',
      location: 'body'
    }
  ]
}

And this is the errors.array():

[
  {
    value: 'b',
    msg: 'Username Must be Between 5 to 255 Characters Long!',
    param: 'username',
    location: 'body'
  }
]

I know that I can just use res.status(400).json({ error: errors.array() }); in the Express-Validator and avoid all these but I would prefer if it was passed to next() and handled by the error middleware.

Is there any way to do so or should I just go with the other way?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you see the below code, this is what is happening. You are passing an array of objects.

let status = new Error([{}]);
console.log(status); // Error: [object Object]

Now, when you check the validation object it is something like this:

// errors will be like
[{ myLocation: 'body' }, { myLocation: 'query' }...]

All you have to make it a string:

const expressValidationError = (req, res, next) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {

    // below is only useful when you don't have array of objects
    // const err = new Error(errors.array().toString());

    const err = new Error(errors.array().map(el => el['msg']).toString());
    err.status = 400;
    next(err);
  } else {
    next();
  }
};

Adding which key has what validation error:

const expressValidationError = (req, res, next) => {
  const errors = validationResult(req);

  if (!errors.isEmpty()) {

    // below is only useful when you don't have array of objects
    // const err = new Error(errors.array().toString());

    const err = new Error(errors.array().map(el => `${el[param]} - has Error: ${el['msg']}`).toString());
    err.status = 400;
    next(err);
  } else {
    next();
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

the problem is not the validator, but that the Error object takes a string parameter as the first parameter, and you're passing it an object (array), hence the object object.

so JSON.stringify the object:

const err = new Error(JSON.stringify(errors.array()));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda