簡體   English   中英

@ControllerAdvice 不捕獲拋出的異常

[英]@ControllerAdvice not catch the thrown exceptions

我使用 java spring。 我嘗試在我的項目中使用 ControllerAdvice 作為全局事件處理程序:

@ControllerAdvice
public class ExceptionsHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(RestClientException.class)
    public void RestClientException(RestClientException ex)
    {
        System.out.println("RestClientException" + ex.getMessage());
    }

    @ExceptionHandler
    public void Exception(Exception ex)
    {
        System.out.println("Exception" + ex.getMessage());
    }
}

在這個 function 我創建並拋出異常:

@Component
@RequiredArgsConstructor
public class Scheduler {

    public void schedule() throws JsonProcessingException, Exception {
            throw new Exception();
    }
}

和:

@Component
@RequiredArgsConstructor
public class RestfulReaderServiceImpl implements RestfulReaderService {

    public String getData(String url) throws RestClientException {
        throw new RestClientException();
    }
}   

但是當這些函數被觸發並拋出異常時,class ExceptionsHandler 中的異常處理程序不會執行。

知道為什么 ExceptionsHandler class 中的異常處理程序不捕獲並處理異常嗎?

@ControllerAdvice僅處理從 Controller 方法拋出的異常,即使用@RequestMapping或其任何快捷方式注釋( @GetMapping等)注釋的方法。 您可以通過從任何@RequestMapping注釋方法調用異常拋出方法來檢查這一點。

暫無
暫無

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

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