You need to enable JavaScript to run this app. SpringBoot DTO字段@Size校验自定义提示及冗长报错原因求解
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot DTO字段@Size校验自定义提示及冗长报错原因求解

冗余错误返回原因

Spring Boot 未配置自定义校验异常处理器时,@Valid 触发参数校验失败后抛出的 MethodArgumentNotValidException 会被默认的异常序列化逻辑直接处理,将整个异常的完整上下文(包括方法签名、校验码、参数对象信息等)全部返回,你定义的 @Size 自定义提示信息已经存在于返回结果中,只是被包裹在了大量冗余的异常信息内。

解决方案

新增全局异常处理器,捕获校验异常后手动提取注解内的自定义提示返回即可,示例代码如下:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        HashMap<String, Object> result = new HashMap<>();
        HashMap<String, String> fieldErrors = new HashMap<>();
        // 遍历所有校验错误,提取字段名和对应的自定义提示
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String field = ((FieldError) error).getField();
            String message = error.getDefaultMessage();
            fieldErrors.put(field, message);
        });
        // 可根据你的业务错误格式调整返回结构
        result.put("code", "400");
        result.put("message", "参数校验失败");
        result.put("errors", fieldErrors);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
}

调整后触发校验的返回效果示例:

{
    "code": "400",
    "message": "参数校验失败",
    "errors": {
        "login": "'Login' value '56dtttttttttt444444444465st' must be between 1 and 20 characters long."
    }
}
额外优化建议

你当前的DTO字段上同时标注了@NotNull、@NotEmpty、@Size(min = 1),其中@NotEmpty本身已经包含了「非null」和「字符串长度≥1」的校验规则,可删除重复的@NotNull和@Size(min = 1)配置,减少不必要的重复校验。

内容的提问来源于stack exchange,提问作者Peter Penzov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 01:36:06