spring boot validator doesnt return custom error message

83 views Asked by At

I would like to compare two fields in my entity and check if maxField is greater than minField to be valid. Below is my implementation but I cannot see the custom message, instead it returns this with 400 bad request:

{
    "errors": []
}

my dto:

@ValidMaxMinDouble(
    maxFieldName = "maxOperatingTemperature",
    minFieldName = "minOperatingTemperature",
    message =
        "Maximum operating temperature must not be less than the minimum operating temperature")
@Data
public class RequestDTO {

  @ValidDoubleRange(min = -100, max = 100, required = true)
  private Double maxOperatingTemperature;

  @ValidDoubleRange(min = -100, max = 100, required = true)
  private Double minOperatingTemperature;
}

and here is my validator:

@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidMaxMinDoubleValidator.class)
public @interface ValidMaxMinDouble {
  String message() default "The maximum value must be greater than or equal to the minimum value";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};

  String maxFieldName();

  String minFieldName();

  @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
  @Retention(RetentionPolicy.RUNTIME)
  @interface List {
    ValidMaxMinDouble[] value();
  }
}

class ValidMaxMinDoubleValidator implements ConstraintValidator<ValidMaxMinDouble, Object> {
  private String maxFieldName;
  private String minFieldName;
  private String message;

  @Override
  public void initialize(ValidMaxMinDouble constraintAnnotation) {
    this.maxFieldName = constraintAnnotation.maxFieldName();
    this.minFieldName = constraintAnnotation.minFieldName();
    this.message = constraintAnnotation.message();
  }

  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {
    Double maxValue = (Double) new BeanWrapperImpl(value).getPropertyValue(maxFieldName);
    Double minValue = (Double) new BeanWrapperImpl(value).getPropertyValue(minFieldName);

    if (maxValue == null || minValue == null) {
      return false;
    }

    boolean valid = maxValue >= minValue;
    if (!valid && !message.isEmpty()) {
      context.disableDefaultConstraintViolation();
      context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
    }

    return valid;
  }
}

I cannot see whay I cannot see custom error message. The request I sent triggers context.disabledisableDefaultConstraintViolation() part.

1

There are 1 answers

0
Salvatore Bernardo On

I replicated here https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77724410 the case.

Dependencies pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Validation -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <!-- Swagger UI for test -->
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
        <version>${springdoc-openapi.version}</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

I also added a @ControllerAdvice to intercept all errors and return a BadRequest with custom messages. You can customize response structure.

Let me know if miss something, hope this will help ;)