Springboot
项目中实现全局异常处理
自定义异常
public class UserNameAndPasswordException extends RuntimeException{
protected Integer errorCode;
protected String errorMsg;
public UserNameAndPasswordException() {
}
public UserNameAndPasswordException(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public UserNameAndPasswordException(String message, Integer errorCode, String errorMsg) {
super(message);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
}
全局异常处理器:
// ControllerAdvice 注解,AOP实现,拦截异常
@ControllerAdvice
public class TestExceptionHandler {
// value可以是一个数组
@ExceptionHandler(value = UserNameAndPasswordException.class)
@ResponseBody
public ResponseEntity userNameAndPwdExceptionHandler(UserNameAndPasswordException e) {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("errorCode", e.getErrorCode());
errorMap.put("errorMSg", e.getErrorMsg());
return new ResponseEntity(errorMap, HttpStatus.UNAUTHORIZED);
}
}