所以我在我的Spring Boot服務中定義了各種 API 端點,它們會拋出各種自定義例外。但我無法區分Checked和Unchecked例外。
那么我的自定義例外應該是Checked還是Unchecked例外?
例子:
- UserNotFoundException
- EmailAlreadyExistsException
- JWTTokenMalformedException
- 資料庫節點故障例外
這些例外由 Spring 決議ControllerAdvice,轉換為 ResponseEntity 并發送給客戶端。
您如何將上述自定義創建的例外定義為Checked或Unchecked?還讓我知道是否有任何經驗法則可以決定您的例外是Checked還是Unchecked?
uj5u.com熱心網友回復:
即使您有所有例外,您也很好,RuntimeException因為您將錯誤回應生成委托給ControllerAdvice. 無論它是 RESTful Spring Boot 服務還是只是另一個 Java 應用程式,從方法中拋出 Checked 或 Unchecked 例外的前提很大程度上取決于呼叫者是 MUST(Checked)還是 SHALL(Runtime)處理例外。
例如呼叫時
FileInputStream fis = new FileInputStream("somefile.txt");
建構式FileInputStream(String fileName)強制處理 File not found 例外情況。因此,它會拋出一個FileNotFoundException已檢查例外,并且必須由呼叫者在呼叫位置本身處理。
uj5u.com熱心網友回復:
嘗試將它們全部定義為未選中,并為需要特定處理的每種例外型別定義一個方法@ExceptionHandlerinControllerAdvice
@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
uj5u.com熱心網友回復:
還讓我知道是否有任何經驗法則可以決定您的例外是選中還是未選中?
Checked Exception 編譯器檢查并強制您處理例外
Unchecked Exception 編譯器不會警告你,你自己處理例外
您可以采用的規則如下
- 如果您處于依賴關系的情況下,例如您必須通過許多層處理業務規則,則使用
Checked Exception. 它會迫使你在頂層處理你的例外(服務>控制器) - 如果您無法控制應用程式或架構的某些方面,例如訪問服務器或某個位置的可用檔案
閱讀本文了解更多詳情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422472.html
標籤:
上一篇:使用多個搜索引數實作搜索功能
