异常处理
public interface baseErrorInfoInterface {
String getResultCode();
String getResultMsg();
}
枚举类
public enum ExceptionEnum implements baseErrorInfoInterface{
// 数据操作错误定义
BODY_NOT_MATCH("4000","请求的数据格式不符!");
private final String resultCode;
private final String resultMsg;
ExceptionEnum(String resultCode, String resultMsg) {
this.resultCode = resultCode;
this.resultMsg = resultMsg;
}
@Override
public String getResultCode() {
return resultCode;
}
@Override
public String getResultMsg() {
return resultMsg;
}
}
捕获全局异常
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = BizException.class)
@ResponseBody
public Result bizExceptionHandler(HttpServletRequest req, BizException e){
logger.error("发生业务异常!原因是:{}",e.getErrorMsg());
return Result.fail(e.getErrorMsg());
}
@ExceptionHandler(value =NullPointerException.class)
@ResponseBody
public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
logger.error("发生空指针异常!原因是:",e);
return Result.fail(ExceptionEnum.BODY_NOT_MATCH);
}
// @ExceptionHandler(value =Exception.class)
// @ResponseBody
// public ResultResponse exceptionHandler(HttpServletRequest req, Exception e){
// logger.error("未知异常!原因是:",e);
// return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
// }
}
异常处理类
public class BizException extends RuntimeException{
private static final long serialVersionUID = 1L;
protected String errorCode;
protected String errorMsg;
public BizException() {
super();
}
public BizException(baseErrorInfoInterface errorInfoInterface) {
super(errorInfoInterface.getResultCode());
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}
public BizException(baseErrorInfoInterface errorInfoInterface, Throwable cause) {
super(errorInfoInterface.getResultCode(), cause);
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}
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 String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}



