簡體   English   中英

如何使用@ControllerAdvice 從服務類中捕獲異常?

[英]How to use @ControllerAdvice for catching exceptions from Service classes?

我有一些服務類,其中包含多個拋出錯誤的方法,一個拋出錯誤的方法示例:

public Optional<Item> getItemById(Long itemId) throws Exception {
        return Optional.of(itemRepository.findById(itemId).
                orElseThrow(() -> new Exception("Item with that id doesn't exist")));
    }

我應該在注釋為 class 的 @ControllerAdvice 中捕獲錯誤嗎? 我應該怎么做?

標有@ControllerAdvice 的 controller 將攔截在請求到達時調用的堆棧中拋出的任何異常。 如果問題是您是否應該使用 ControllerAdvice 捕獲錯誤,這取決於您,但它允許您在拋出異常后自定義行為。 為此,您應該像這樣創建一個 class:

@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler({ Exception.class, MyCustomException.class }) //Which exceptions should this method intercept
  public final ResponseEntity<ApiError> handleException(Exception ex){
    return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); //Or any HTTP error you want to return
  }

}

暫無
暫無

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

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