Wednesday, May 5, 2021

Handling Exceptions in EJB using Interceptors

In my previous posts Using EJB Interceptors to add functionality to existing Beans, and Using EJB Interceptors to execute code AFTER service method completes, we saw how to use EJB3 Interceptors to add common concern features like logging, etc. to J2EE service methods.
In case you want to have common exception handling logic for all service method calls, you can wrap the return context.proceed(); in a try-catch block and handle the exception in the catch block as shown below:


package com.my.ejb.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {

    @AroundInvoke
    public Object interceptorMethod(InvocationContext context) throws Exception {
    	try {
          System.out.println("Before invoking method: " + context.getMethod());
          return context.proceed();
        } catch (Exception e) { // You can catch ALL or ONLY Specific Exceptions as per your requirement
          System.out.println("Exception in method " + context.getMethod() + ": " + e.getMessage());
        } finally {
          System.out.println("After invoking method: " + context.getMethod());
        }
    }
}

Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:

import javax.interceptor.Interceptors;

@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})

Now you should see log lines "Before ..." before the the method executes and "After..." after the method executes and in case of any exceptions in the metod call, you will see "Exception ..."


No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...