1.首先自定义自己的exceptHandler,在类上添加一个@controllerAdvice 这个注释可以捕获所有异常,在类中添加一个方法直接返回异常即可。
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(value =Exception.class)
@ResponseBody
public String exceptionHandler(Exception e){
return "ExceptHandler:全局异常捕获,错误原因>>>"+e.getMessage();
}
}
2.枚举自己定义的异常编码,和异常信息,BaseError自己定义下,就编码和信息2个值,个人感觉直接用枚举也可以
/**
* @description: 异常处理枚举类
*/
public enum ExceptionEnum implements BaseError{
// 数据操作错误定义
SUCCESS("200", "成功!"),
BODY_NOT_MATCH("400","请求的数据格式不符!"),
/**
* 错误码
*/
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;
}
}
3.定义业务中使用的异常类,
/**
* @description: 默认使用的自定义异常类
*/
public class BizException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* 错误码
*/
protected String errorCode;
/**
* 错误信息
*/
protected String errorMsg;
public BizException() {
super();
}
public BizException(BaseError erro) {
super(error.getResultCode());
this.errorCode = error.getResultCode();
this.errorMsg = error.getResultMsg();
}
public BizException(BaseError , Throwable cause) {
super(error.getResultCode(), cause);
this.errorCode = error.getResultCode();
this.errorMsg = error.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;
}
4.具体使用 这个不建议自己写字符串,可以写到ExceptionEnum枚举中,直接在枚举中拿,而且可以自己添加
if(user.getName()==null){
throw new BizException("-1","用户姓名不能为空!");
}