一、什么是统一异常处理
1、制造异常
除以0
int a = 10/0;
2、什么是统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理
二、统一异常处理
1、创建统一异常处理器
在service-base中创建统一异常处理类GlobalExceptionHandler.java:
/*** 统一异常处理类*/@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(Exception.class)@ResponseBodypublic R error(Exception e){e.printStackTrace();return R.error();}}
2、测试
返回统一错误结果
三、处理特定异常
1、添加异常处理方法
GlobalExceptionHandler.java中添加
@ExceptionHandler(ArithmeticException.class)@ResponseBodypublic R error(ArithmeticException e){e.printStackTrace();return R.error().message("执行了自定义异常");}
2、测试

四、自定义异常
1、创建自定义异常类
@Data@AllArgsConstructor@NoArgsConstructorpublic class GuliException extends RuntimeException {@ApiModelProperty(value = "状态码")private Integer code;private String msg;}
2、业务中需要的位置抛出GuliException
try {int a = 10/0;}catch(Exception e) {throw new GuliException(20001,"出现自定义异常");}
3、添加异常处理方法
GlobalExceptionHandler.java中添加
@ExceptionHandler(GuliException.class)@ResponseBodypublic R error(GuliException e){e.printStackTrace();return R.error().message(e.getMsg()).code(e.getCode());}

