簡體   English   中英

使用@ControllerAdvice處理Spring Exception提供了集中控制,但是我們必須在方法簽名中添加所有throws異常

[英]Spring Exception handling with @ControllerAdvice provides centralized control but we have to add all throws exception in method signature

使用@ControllerAdvice處理Spring Exception提供了集中控制,但是我們必須在方法簽名中添加所有throws異常

例如

  public void methodA() throws feign.FeignException,IOException,InterruptedException,ExecutionException{ //CODE } 
ExceptionHandler
@ControllerAdvice
public class SpringExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value={feign.FeignException.class})
    public ResponseEntity<ErrorMsg> handleFeignException(Exception ex, WebRequest request){
     //CODE..
}
@ExceptionHandler(value={TimeoutException.class})
    public ResponseEntity<ErrorMsg> handleTimeoutException(Exception ex, WebRequest request){
     //CODE..
}
@ExceptionHandler(value={Exception.class})
    public ResponseEntity<ErrorMsg> handleGenericException(Exception ex, WebRequest request){
     //CODE..
}
}

這是將所有引發異常添加到方法簽名中的推薦方法嗎? 請讓我知道是否有更好的或建議的方法來聲明引發異常。

我沒有這種方法的問題,但春季啟動代碼/ API方法 簽名看起來不同或冗長。

您可以從任意位置拋出異常-如果前提條件失敗,則可以在內部方法中拋出異常

https://github.com/dhananjay12/learning-spring-rest/blob/master/error-handling/src/main/java/com/djcodes/spring/rest/errorhandling/EmployeeController.java

或方法簽名中。

處理Feignexception可能會有些棘手。 我建議您閱讀這篇文章-https://source.coveo.com/2016/02/19/microservices-and-exception-handling/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM