javax.validation包校驗巢狀屬性(List物件)的寫法

linzm14發表於2024-08-06

1 maven依賴

        <!-- Hibernate Validator 用於資料驗證 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2 controller 請求實體

@Slf4j
@Validated
public class TestController {

    @PostMapping(value = "/v1/chat/completions")
    public Flux<AgentChatVo> chat(@Valid @RequestBody AgentChatRequest request) {
        return agentServiceService.chat(request);
    }
}

@Data
public class AgentChatRequest {
    @Schema(description = "")
    private String model;

    @Schema(description = "是否開啟stream模式")
    private Boolean stream = false;

    @NotEmpty(message = "The messages cannot be null.")
    @Valid
    private List<Message> messages;

    @ApiModelProperty(hidden = true, value = "aigc 是否使用 ")
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private Boolean context = false;

    @Schema(description = "最大長度")
    @JsonProperty(value = "max_tokens")
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private String maxTokens;
}

@Data
public class Message {
    @Schema(description = "角色")
    @ApiModelProperty(hidden = true)
    private String role;

    @Schema(description = "問題內容")
    @NotBlank(message = "The content cannot be blank.")
    private String content;

    public void initRole() {
        if (StringUtils.isBlank(this.role)) {
            this.role = AiChatRoleEnum.USER.getCode();
        }
    }
}

3 GlobalExceptionHandler

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler implements ResponseBodyAdvice, RequestBodyAdvice {
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Result<Void>> errHandler(MethodArgumentNotValidException exception) {
        log.error("MethodArgumentNotValidException e:", exception);
        String errorMsg = paramException(exception.getBindingResult());
        return ResponseEntity.status(HttpStatus.OK).body(Result.fail(ResultCodeEnum.PARAM_ILLEGAL.code(), errorMsg));
    }

    private String paramException(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            if (StringUtils.isNotBlank(defaultMessage)) {
                errorMsg.append(
                    String.format("%s的 %s 欄位異常: %s;",  "入參實體", fieldError.getField(), defaultMessage));
            } else {
                errorMsg.append(
                    String.format("%s的%s欄位不能被賦值為%s;",  "入參實體", fieldError.getField(),
                        fieldError.getRejectedValue()));
            }
        }
        return errorMsg.toString();
    }
}

4 測試


相關文章