@ControllerAdvice 没有捕获抛出的异常

时间:2021-03-08 04:36:32

标签: java spring-mvc

我使用 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());
    }
}

在这个函数中,我创建并抛出一个异常:

@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();
    }
}   

但是当这些函数被触发并抛出异常时,异常处理程序 在 ExceptionsHandler 类中不执行。

知道为什么 ExceptionsHandler 类中的异常处理程序不捕获并处理 例外?

1 个答案:

答案 0 :(得分:0)

@ControllerAdvice 仅处理从 Controller 方法抛出的异常,即用 @RequestMapping 或其任何快捷注释(@GetMapping 等)注释的方法。您可以通过从任何 @RequestMapping 注释方法调用异常抛出方法来检查这一点。