spring boot 统一异常处理实际是使用aop,在controller层添加异常处理
1,声明一个切面
2,添加异常处理
1.声明切面,在类上添加@RestControllerAdvice 或 @ ControllerAdvice
2.添加异常处理,在方法上添加注解 @ExceptionHandler()
如果是多个异常一起处理,使用{},表示数组,之间用","隔开,如
@ExceptionHandler({DataIntegrityViolationException.class,NullPointerException.class})
当多个异常处理器时,以最准的异常捕捉起作用,即在异常继承关系中,子异常优于父异常
完整代码如下
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({Exception.class})
public RespDto globalException(Exception e){
e.printStackTrace();
return RespBuilder.error(e.getClass().getName(),e.getMessage());
}
@ExceptionHandler(DuplicateKeyException.class)
public RespDto duplicateKey(Exception e){
e.printStackTrace();
return RespBuilder.error("插入失败,违反唯一约束",e.getMessage());
}
@ExceptionHandler(DataIntegrityViolationException.class)
public RespDto insertNull(Exception e){
e.printStackTrace();
return RespBuilder.error("缺少参数或参数值为null",e.getMessage());
}
}