简体   繁体   English

@ControllerAdvice 不捕获抛出的异常

[英]@ControllerAdvice not catch the thrown exceptions

I use java spring.我使用 java spring。 I try to use ControllerAdvice in my project as a global event handler:我尝试在我的项目中使用 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());
    }
}

In this function I create and throw an exception:在这个 function 我创建并抛出异常:

@Component
@RequiredArgsConstructor
public class Scheduler {

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

And:和:

@Component
@RequiredArgsConstructor
public class RestfulReaderServiceImpl implements RestfulReaderService {

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

But when those functions are fired and exceptions are thrown the exception handlers in class ExceptionsHandler does not execute.但是当这些函数被触发并抛出异常时,class ExceptionsHandler 中的异常处理程序不会执行。

Any idea why exception handlers in ExceptionsHandler class not catches and handles the exceptions?知道为什么 ExceptionsHandler class 中的异常处理程序不捕获并处理异常吗?

@ControllerAdvice only handles exceptions thrown from Controller methods ie methods annotated with @RequestMapping or any of its shortcut annotations ( @GetMapping etc.). @ControllerAdvice仅处理从 Controller 方法抛出的异常,即使用@RequestMapping或其任何快捷方式注释( @GetMapping等)注释的方法。 You can check this by calling your exception throwing method from any @RequestMapping annotated method.您可以通过从任何@RequestMapping注释方法调用异常抛出方法来检查这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM