springboot创建统一异常拦截器全局处理 异常

1.创建Exception类   

public class MyException extends RuntimeException {
private ErrorCodeEnum errorCode;

public MyException(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}

public ErrorCodeEnum getErrorCode() {
return errorCode;
}

public void setErrorCode(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}
}

2.异常枚举类  
public enum ErrorCodeEnum {
INCORRECT_PASSWORD(10001, "密码错误!"),
INUSED_USER(10002, "账号错误!"),
INCORRECT_MSG(10003, "验证码错误!"),

ErrorCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}

private int code;
private String msg;

public int getCode() {
return code;
}

public String getMsg() {
return msg;
}
}




3.全局异常处理类
@ControllerAdvice
public class MyExceptionHandler {
   //捕捉到的异常
@ExceptionHandler(value = MyException.class)
public ResponseEntity<Result> handleServiceException(MyException exception) {
ErrorCodeEnum errorCode = exception.getErrorCode();
return new ResponseEntity(new ResultUtil<String>().setError(errorCode.getCode(), errorCode.getMsg(), ""), HttpStatus.BAD_REQUEST);
}
    //其他异常
@ExceptionHandler
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Result> hadleServerException(Exception exception) {
exception.printStackTrace();
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
String msg = "server error, please try again later";
Class exceptionClazz = exception.getClass();
if (Objects.equals(MissingServletRequestParameterException.class, exceptionClazz)) {
msg = "incorrect parameter";
httpStatus = HttpStatus.BAD_REQUEST;
} else if (Objects.equals(HttpRequestMethodNotSupportedException.class, exceptionClazz)) {
httpStatus = HttpStatus.BAD_REQUEST;
msg = exception.getMessage();
}
return new ResponseEntity(new ResultUtil<String>().setError(httpStatus.value(), msg, ""), httpStatus);
}
}
原文地址:https://www.cnblogs.com/java-xz/p/9173325.html