如何在Spring Boot Service层实现数据校验并仅返回自定义错误信息
问题根因
当前你触发的是JPA持久化阶段的自动校验,捕获异常后直接返回e.getMessage(),该内容默认包含类路径、属性名等附加信息,没有单独提取注解里配置的自定义错误信息,所以出现多余内容。
解决方案
1. 引入校验依赖(未添加时需要)
Maven配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2. 调整校验逻辑(二选一即可)
方案1:Service层主动校验(可控性最高)
修改UserServicesImpl类,主动执行校验提取错误信息:
@Service @Transactional public class UserServicesImpl implements UserService{ @Autowired UserRepository userRepository; // 注入校验器 @Autowired Validator validator; @Override public Users registerUser(String first_name, String last_name) throws EtAuthException { // 构造实体对象 Users user = new Users(first_name, last_name); // 执行校验 Set<ConstraintViolation<Users>> violations = validator.validate(user); if (!violations.isEmpty()) { // 仅提取注解配置的错误信息 List<String> errorMsgs = violations.stream() .map(ConstraintViolation::getMessage) .collect(Collectors.toList()); // 可自定义异常接收错误列表,此处示例转JSON字符串抛出 throw new EtAuthException(new ObjectMapper().writeValueAsString(errorMsgs)); } // 修复原代码笔误:first_namea改为first_name Integer userId = userRepository.create(first_name, last_name); return userRepository.findById(userId); } }
方案2:全局异常统一处理(更简洁)
新增全局异常处理器,统一拦截校验异常格式化返回:
@RestControllerAdvice public class GlobalExceptionHandler { // 拦截JSR校验异常 @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<Map<String, List<String>>> handleValidationError(ConstraintViolationException e) { List<String> errors = e.getConstraintViolations() .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.toList()); Map<String, List<String>> res = new HashMap<>(); res.put("message", errors); return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); } }
同时给UserServicesImpl类添加@Validated注解,触发方法级校验即可。
最终效果
校验失败时返回格式和要求完全一致:
{"message": ["First name can not be empty","Last name can not be empty"]}
内容的提问来源于stack exchange,提问作者RajB009
相关产品推荐
相关产品推荐

