validation捕获异常
好像需要在控制器启用校验才能捕获参数校验,即
@RestController
@Validated
----------------------分隔符-----------------------------
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.xfstu.rbac.response.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@RestControllerAdvice
public class GlobalError {
// 捕获方法参数校验异常
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ResponseEntity<Response<?>> constraintViolationExceptionHandler(ConstraintViolationException e){
Set<ConstraintViolation<?>> message = e.getConstraintViolations();
List<String> errorMessages = new ArrayList<>();
message.stream().forEach(msg -> {
errorMessages.add(msg.getMessage());
});
Response<String> errorResponse=Response.error(errorMessages.get(0),400);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
// 捕获实体参数校验异常
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResponseEntity<Response<?>> handleBindException(MethodArgumentNotValidException ex) {
String fieldError = ex.getBindingResult().getFieldError().getDefaultMessage();
Response<String> errorResponse=Response.error(fieldError,400);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
//全局异常
@ExceptionHandler(Exception.class)
public ResponseEntity<Response<?>> handleException(Exception ex) {
System.out.println("异常类"+ex.getClass().getName());
ex.printStackTrace();
Response<?> errorResponse=Response.error("Something went wrong."+ex.getMessage(),500);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
不是专业的写法
本文来自博客园,作者:小枫同学,除网络转载的部分,其他版权属于作者和博客园所有,未经作者或博客园许可,禁止转载、复制、重新发布完整或者部分文字、代码、图片等信息,否则将保留追究法律责任的权利(如博客侵权了您的作品,本人再次表示抱歉,请将原创地址发送至下文邮箱,核实后立刻删除。)。查阅文章的同学,由于网络爬虫严重,有些代码并不会完整贴出来或者存在bug,不过你可以发送邮件到xfstune@126.com获取新代码,记得附上文章链接