SpringBoot异常的设计的原理
Spring Boot的统一异常处理设计
在Spring Boot中支持RestControllerAdvice((ControllerAdvice))统一处理异常,如果controller或者service出现异常都会被RestControllerAdvice统一捕获将异常信息转换中更容易识别的格式后输出
当我们定义了一个自定义返回参数格式时,希望得到统一的返回,如果在运行时发现了异常,也希望将异常统一返回。
通常用于定义@ExceptionHandler, @InitBinder 和 @ModelAttribute 适用于所有@RequestMapping方法的方法。
启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 @RequestMapping 注解的方法上。
全局异常捕捉处理
1、自定义异常类
@Data
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code ;
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
}
2、定义全局异常捕捉类
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
@ExceptionHandler(MyException .class)
public R apiExceptionHandler(MyException ex) {
log.error("ApiException 异常抛出:{}", ex);
return R.fail(ex);
}
}
3、随便写一个RequestMapping抛出异常时,返回的参数可以统一格式
@GetMapping("test")
public R test(@RequestParam Integer id) {
if (id == null) {
throw new MyException("参数不存在",100);
}
return new R();
}
返回的参数
{
“msg”: “参数不存在”,
“code”: 100
}