[英]Exception Handling in RESTful Spring Boot Services
因此,我在 Spring 引導服務中定義了各種 API 端點,這些端點會引發各種自定義異常。 但我無法區分 Checked 和 Unchecked 的異常。
那么我的自定義異常應該被檢查還是未經檢查的異常?
例子:
這些異常由 Springs controllerAdvice 解析,轉換為 ResponseEntity 並發送給客戶端。
您如何將上述自定義創建的異常定義為選中或未選中? 還讓我知道是否有任何經驗法則來決定是否應該檢查或不檢查您的異常?
即使您將所有異常都作為RuntimeException
也很好,因為您將錯誤響應生成委托給ControllerAdvice
。 無論是 RESTful Spring 引導服務還是只是另一個 Java 應用程序,從方法中拋出已檢查或未檢查異常的前提很大程度上取決於調用者是否必須(已檢查)或應(運行時)處理異常。
例如調用時
FileInputStream fis = new FileInputStream("somefile.txt");
構造函數FileInputStream(String fileName)
強制處理 File not found 異常情況。 因此它會拋出一個FileNotFoundException
,這是一個檢查異常,必須由調用者在調用位置本身處理。
嘗試將它們全部定義為未選中,並為需要在ControllerAdvice
中使用@ExceptionHandler
進行特定處理的每種異常類型定義一個方法
@ExceptionHandler(value = { EmailAlreadyExistsException.class, UserAlreadyExistsException.class })
protected ResponseEntity<Object> handleAlreadyExistsException(RuntimeException ex, WebRequest request) {
String yourErrMsg = "Some error desc.."
List<String> errorMessages = List.of(yourErrMsg);
HttpStatus httpStatusForTheError = HttpStatus.BAD_REQUEST;
return new ResponseEntity<List<String>>
(errorMessages, httpStatusForTheError);
}
最后一種方法是包羅萬象
@ExceptionHandler(value = RuntimeException.class)
protected ResponseEntity<Object> handle EmailAlreadyExistsException(RuntimeException ex, WebRequest request) {
String yourErrMsg = "We are sorry, something went wrong."//don't disclose the stacktrace
List<String> errorMessages = List.of(yourErrMsg);
return new ResponseEntity<List<String>>
(errorMessages, HttpStatus.INTERNAL_SERVER_ERROR);
}
示例來自: https://www.baeldung.com/exception-handling-for-rest-with-spring
還讓我知道是否有任何經驗法則可以決定您的異常是選中還是未選中?
Checked Exception
編譯器檢查並強制你處理異常
Unchecked Exception
編譯器不會警告你,你自己處理異常
您可以采用的規則如下
Checked Exception
。 它會迫使你在頂層處理你的異常(服務>控制器)閱讀本文了解更多詳情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.