【问题标题】:@ExceptionHandler not working in a Service class@ExceptionHandler 不在服务类中工作
【发布时间】:2020-09-16 05:55:44
【问题描述】:

下面是一个服务类

@Service
class Test {

    public Object findEmployees1(String id, String dbId) {
        return employeeRepo.findByDatabaseIdAndIdentifier(dbId, id);

    }
    
        public Object findEmployees2(String name, String dbId) {
        Object records = employeeRepo.findByNameAndDatabaseId(name, dbId);

    }
    
    
        @ExceptionHandler(Exception.class)
        public void internalErrorExceptionHandler(Exception ex) {
        LOGGER.error("Log the exception here");
        throw new InternalErrorException(ex.getMessage());
    }
}

我希望如果类 test 中的任何方法中出现任何异常(例如一些 SQLException),它会被 @ExceptionHandler 捕获并记录在那里并重新抛出

我不能将@ExceptionHandler@ControllerAdvice 一起使用,因为我没有任何带有@Controller 注释的类。我只是在编写一个通用模块来从数据库中获取数据。

当我执行代码时,@ExceptionHandler 下的日志不会被打印,因为它永远不会被调用。 要求是在任何服务类方法中出现任何异常时记录并重新引发常见异常,而每个方法中没有单独的 try catch 语句。

【问题讨论】:

  • @ExceptionHandler 是一个仅限网络的注释,否则将不起作用。
  • @M.Deinum - 有没有其他方法可以在服务类中实现相同的目标?
  • 为此使用 AOP。

标签: spring-boot exception exceptionhandler


【解决方案1】:

按照建议,您可以使用 spring aop 来处理此类异常。我不会重复,而是链接到我试图回答的现有问题here

另一种方法是,如果您使用的是 ByteBuddy,您可以在预期抛出异常的方法上使用以下注解。

@Advice.OnMethodExit(onThrowable = RuntimeException.class)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多