【发布时间】: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