0

The below is a service class

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

I want if any exception(eg some SQLException) comes in any of the method in the class test , it gets caught by the @ExceptionHandler and is logged there and re thrown

I cannot use @ExceptionHandler with @ControllerAdvice as I don't have any class with @Controller annotation on it . I am writing just a common module to get data from the database.

When I execute the code , the log under @ExceptionHandler is not printed as it never gets called. The requirement is to log and rethrow a common exception if any exception comes in any of the service class methods without having individual try catch statements in each method.

Jackson
  • 75
  • 6

1 Answers1

0

As suggested, you can use spring aop to handle such exceptions. Instead of duplicating I will link to the existing question I have tried to answer here.

The other way is, if you are using ByteBuddy, you can use following annotation on the method which is expected to throw exception.

@Advice.OnMethodExit(onThrowable = RuntimeException.class)
silentsudo
  • 6,730
  • 6
  • 39
  • 81