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

1.6K
Vistas
How Can I throw exceptions using FluentValidation .net 6?

I migrated my web api from asp net core 3.1 to .net 6 and I'm having some issues with the using FluentValidation library.

RuleFor(x => x.Name)
            .NotEmpty()
            .OnFailure(x =>
            {
                var message = "El nombre del Usuario es requerido.";
                throw new HttpException(message, message, (int)HttpStatusCode.BadRequest);
            })
            .Length(1, 150)
            .OnFailure(x =>
            {
                var message = "El nombre del Usuario debe contener hasta máximo 150 caracteres.";
                throw new HttpException(message, message, (int)HttpStatusCode.BadRequest);
            });

This code used to work correctly but, when I updated the library , the method .OnFailure() is deprecated.

I would like to know how can I throw a custom exception for each OnFailure as I used to do it, where HttpException is a custom class that inherited from Exception. An example of json result would be:

    {
  "developerMessage": "El nombre del Usuario es requerido..",
  "userMessage": "El nombre del Usuario es requerido.",
  "errorCode": 400,
  "moreInfo": ""
   }

UPDATED!

I followed this article https://www.tutorialspoint.com/what-is-use-of-fluent-validation-in-chash-and-how-to-use-in-chash. I used CascadeMode.Stop because the previous one is deprecated but, when I try testing .Lenght validation, the result variable shows the firt error of each RuleFor(). I mean: If I have 3 RuleFor() and each rule has 2 validators, the result variable shows the first error message's validator of each RuleFor() and no error message of the real failure.

How can I solve this?

public UserValidator()
{
  RuleFor(x => x.Name)
                .Cascade(CascadeMode.Stop)
                .NotEmpty().WithMessage("El nombre del Usuario es requerido.")
                .Length(1, 150).WithMessage("El nombre del Usuario debe contener hasta máximo 150 caracteres.");

  var result = Validate(new User()); //I need to get the context (user) to validate it , **not new User()**
        if(!result.IsValid)
        {
            foreach(var error in result.Errors)
            {
                var message = $"{error.ErrorMessage}";
                throw new HttpException(message, message, (int)HttpStatusCode.BadRequest);
            }
        }
}
over 4 years ago · Santiago Trujillo
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