Spring Boot 验证器不返回自定义错误消息

问题描述 投票:0回答:1

我想比较实体中的两个字段,并检查 maxField 是否大于 minField 才有效。下面是我的实现,但我看不到自定义消息,而是返回了 400 bad request:

{
    "errors": []
}

我的 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;
}

这是我的验证器:

@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;
  }
}

我看不到为什么看不到自定义错误消息。我发送的请求触发了 context.disabledisableDefaultConstraintViolation() 部分。

java spring-boot hibernate-validator customvalidator
1个回答
0
投票

我在这里复制了https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77724410案例。

依赖项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>

我还添加了一个

@ControllerAdvice
来拦截所有错误并返回带有自定义消息的
BadRequest
。您可以自定义响应结构。

如果错过了什么,请告诉我,希望这会有所帮助;)

© www.soinside.com 2019 - 2024. All rights reserved.