Kiran A B
Kiran A B

Reputation: 931

Invoke Method Using Custom Annotation - JAVA

I'm building a generic exception handler in dropwizard. I want to provide custom annotation as part of library, which will invoke a handleException method whenever exception is raised in method(method that contains annotation)

Details: Custom annotation is @ExceptionHandler

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExceptionHandler{
    Class<? extends Throwable>[] exception() default {};
}

There is a handler method handleException(Exception, Request) in class ExceptionHandlerImpl.

Now there's a business class that has method with annotation

@ExceptionHandler(exception = {EXC1,EXC2})
Response doPerformOperation(Request) throws EXC1,EXC2,EXC3{}

Now whenever EXC1 and EXC2 are raised by method doPerformOperation, I want to invoke handleException method.

I tried reading about AOP(AspectJ), Reflection, but not able to figure out the best optimal way to perform this.

Upvotes: 1

Views: 1600

Answers (1)

Kiran A B
Kiran A B

Reputation: 931

I have solved this using aspectj. I have created interface

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HandleExceptionSet {
    HandleException[] exceptionSet();
}

Where HandleException is another annotation. This is to allow array of exceptions.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface HandleException {
    Class<? extends CustomException> exception() default CustomException.class;
}

Now I have a ExceptionHandler class, which has handler. To bind a method to this annotation, I'm using below configuration in module.

bindInterceptor(Matchers.any(), Matchers.annotatedWith(HandleExceptionSet.class), new ExceptionHandler());

I use this annotation in classes, with below snippet.

@HandleExceptionSet(exceptionSet = {
        @HandleException(exception = ArithmeticException.class),
        @HandleException(exception = NullPointerException.class),
        @HandleException(exception = EntityNotFoundException.class)
})
public void method()throws Throwable {
    throw new EntityNotFoundException("EVENT1", "ERR1", "Entity Not Found", "Right", "Wrong");
}

This is working for me right now. Not sure, if this is the best approach.

Is there any better way to achieve this?

Upvotes: 1

Related Questions