3 回答

TA貢獻1785條經驗 獲得超4個贊
如果您希望對 API 進行全局異常處理,并且更喜歡自定義錯誤響應,您可以添加@ControllerAdvice:
@ControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler({ ApiException.class })
protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException ex) {
return new ResponseEntity<>(new ApiErrorResponse(ex.getStatus(), ex.getMessage(), Instant.now()), ex.getStatus());
}
}
// you can put any information you want in ApiErrorResponse
public class ApiErrorResponse {
private final HttpStatus status;
private final String message;
private final Instant timestamp;
public ApiError(HttpStatus status, String message, Instant timestamp) {
this.status= status;
this.message = message;
this.timestamp = timestamp;
}
public HttpStatus getStatus() {
return this.status;
}
public String getMessage() {
return this.message;
}
public Instant getTimestamp() {
return this.timestamp;
}
}
// your custom ApiException class
public class ApiException extends RuntimeException {
private final HttpStatus status;
public ApiException(HttpStatus status, String message) {
super(message);
this.status = status;
}
public HttpStatus getStatus() {
return this.status;
}
}

TA貢獻1796條經驗 獲得超7個贊
如果您需要有限數量的不同錯誤消息,或者您想多次重復使用相同的錯誤消息,那么您只需要這樣:
@ResponseStatus(value = HttpStatus.CONTINUE, reason = "No have content")
public class AppException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
不需要任何額外的類和處理程序。您的代碼將清晰而簡單。
您可以像這樣簡單地提高它:
throw new AppException();

TA貢獻1803條經驗 獲得超6個贊
有多種方法可以實現這一點:
異常處理程序
您可以@ExceptionHandler在控制器中添加帶注釋的方法:
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException() {
//
}
處理程序異常解析器
您還可以實現自定義解析器來攔截所有異常并通過覆蓋doResolveException方法來全局處理它們
可以在此處找到有關上述兩種方法的更多詳細信息:https ://www.baeldung.com/exception-handling-for-rest-with-spring
添加回答
舉報