先讲下面三个注解的作用:
@ControllerAdvice : 可对controller层中被@requestMapping注解的方法进行逻辑处理,一般都用于处理异常
@ExceptionHandler : 自动捕捉controller层中出现的 指定的异常 ,并对异常进行处理
@ResponseBody: 对controller的方法进行返回
1:全局异常处理如下:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public R error(Exception e){
e.getStackTrace();
return R.error().message("全局异常处理!");
}
}
2:特定异常处理如下,类似指定异常处理ArithmeticException.class
@ExceptionHandler(value = ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("全局异常处理!");
}
3:自定义异常处理步骤:也是我们用得最多的处理异常方式
a: 创建一个类继承runtimeExcetion类 ,里面code和message属性
@Data
// lombok提供的有参构造
@AllArgsConstructor
// lombok提供的无参构造
@NoArgsConstructor
public class MyRuntimeException extends RuntimeException{
@ApiModelProperty("状态码")
private Integer code;
@ApiModelProperty("异常信息")
private String message;
}
b:在全局处理类MyRuntimeException.java
中加入自定义处理方法
@ExceptionHandler(value = MyRuntimeException.class)
@ResponseBody
public R error(MyRuntimeException e){
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMessage());
}
c:在业务代码中调用就可以了
try {
int b= 1/0;
} catch (Exception e) {
throw new MyRuntimeException(20000,"出现自定义异常!!!");
}