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);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM