1.场景还原
在项目开发中,对于各种异常都有不同的报错提示或策略,无疑对于用户或者开发来说,是一个很好的用户体验;如何在java定义一个全局异常捕捉呢?
2.实现方案
2.1 自定义一个业务异常类
@Setter
@Getter
public class BizException extends RuntimeException {
private static final long serialVersionUID = -6233506444097954612L;
/**
* 错误码
*/
private String errorCode;
/**
* 错误信息
*/
private String errorMsg;
/**
* 返回错误对象信息
*/
private Object data;
public BizException() {
super();
}
public BizException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public BizException(String errorCode, String errorMsg) {
super(errorCode);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public BizException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public BizException(ResultEnum resultEnum) {
super(resultEnum.code());
this.errorCode = resultEnum.code();
this.errorMsg