为什么要自定义异常呢?
已有的异常,我们无法更改它的信息(比如我们无法添加一个异常code),并且已有的异常是所有人都在用的异常,我们不好对它进行拦截特殊处理。
一、自定义异常
其实异常的种类,我们无法去自定义已经有了,比如Exception,RuntimeExceprion等,我去继承这些类,来实现我们的自己的异常,继承了RuntimeException本质上也就是RuntimeException这种异常了
1-1、BizException
public class BizException extends RuntimeException{
private Integer errCode;
private String errMsg;
public BizException(Integer errCode, String errMsg, Exception e){
super(e);
this.errCode = errCode;
this.errMsg = errMsg;
}
public Integer getErrCode() {
return errCode;
}
public void setErrCode(Integer errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
}
1-2、使用我们的自定义异常
我们直接抛出就可以了
@GetMapping("/exception")
public void fun(){
try {
int i = 1 / 0;
}catch (Exception e){
throw new BizException(500,"系统异常",e);
}
}
二、异常处理器
其实这个很好理解,就是当发生了这种异常,就会进到这个处理器进行处理。
具体怎么处理,我们可以由自己的业务逻辑进行处理。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class BizEceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(BizEceptionHandle.class);
@ExceptionHandler({BizException.class})
public String exec(HttpServletRequest request, BizException e){
// 日志记录
logger.error(request.getRequestURI(),e);
// 给开发者发送一个消息
e.printStackTrace();
// 异常处理
return e.getErrMsg();
}
}
三、其它
一般我们开发都会是封装一个统一返回值给前端的,所以上面的这个exec方法的返回值,我们也可以用我们统一的返回值,因为这个返回值将返回给前端(需要说明的是,即便的异常处理器的返回值和你的方法返回值不同也没有关系,最后以异常处理器为准,但是最好是一致的)
四、B站视频
SpringBoot胡咧咧,文件上传、Excel、HttpClient、日志、异常