0
点赞
收藏
分享

微信扫一扫

统一异常处理

朱小落 2021-09-26 阅读 72

一、什么是统一异常处理

1、制造异常

int a = 10/0;

2、什么是统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理

二、统一异常处理

1、创建统一异常处理器
在service-base中创建统一异常处理类GlobalExceptionHandler.java:

/**
* 统一异常处理类
*/

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e){
e.printStackTrace();
return R.error();
}
}

三、处理特定异常

1、添加异常处理方法
GlobalExceptionHandler.java中添加

@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了自定义异常");
}

四、自定义异常

1、创建自定义异常类

@Data
@AllArgsConstructor
@NoArgsConstructor
public 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、添加异常处理方法

@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}
举报

相关推荐

0 条评论