import com.cpit.ycyt.common.base.api.result.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler {
/**
* 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等,验证失败后抛出的异常是MethodArgumentNotValidException异常
*/
@ExceptionHandler({MethodArgumentNotValidException.class})
public HttpResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
StringBuffer sb = new StringBuffer();
BindingResult bindingResult = e.getBindingResult();
bindingResult.getFieldErrors().forEach(fieldError -> {
String message = fieldError.getDefaultMessage();
sb.append(message+" ");
});
log.info("JSR 数据校验失败, {}",sb.toString());
return HttpResult.asResponse("10000",sb.toString());
}
}
@Valid 注解异常处理
最新推荐文章于 2024-05-04 00:40:16 发布