统一异常处理


一、统一异常处理

1、创建统一异常处理器

在service_base中创建统一异常处理类GlobalExceptionHandler.java
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error().message("执行了全局异常!!!");

    }

    

}

二、处理特定异常

1、添加异常处理方法

GlobalExceptionHandler.java中添加
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
    e.printStackTrace();
    return R.error().message("执行了自定义异常");
}
三、自定义异常

1、创建自定义异常类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class WangException extends RuntimeException{
    @ApiModelProperty(value = "状态码")
    private Integer code;
    private String msg;
}

2、业务中需要的位置抛出WangException 

try {
int a = 10/0;
}catch(Exception e) {
throw new WangException (20001,"出现自定义异常");

}

3、添加异常处理方法

GlobalExceptionHandler.java中添加
@ExceptionHandler(WangException.class)
@ResponseBody
public R error(WangException e){ e.printStackTrace(); return R.error().message(e.getMsg()).code(e.getCode()); }

相关