DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Setting Up a Local Development Environment With IntelliJ, DevContainers, and Amazon Linux 2023
  • IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot
  • How To Approach Dependency Management in Java [Video]
  • NullPointerException in Java: Causes and Ways to Avoid It

Trending

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Beyond Manual Mapping: AI-Orchestrated Governance for Hybrid Cloud
  • Build a Voice Assistant With Gemini Live API
  • Member Spotlight: Shai Almong

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java: Exception Translation with AspectJ

Java: Exception Translation with AspectJ

By 
Michael Scharhag
·
Feb. 04, 14 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
17.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Within this blog post I describe how you can use AspectJ to automatically translate one type of exception to another. 

The problem
Sometimes we are in situations where we have to convert an exception (often thrown by a third-party library) to another type of exception. Assume you are using a persistence framework like hibernate and you do not want to leak hibernate specific exceptions out of a certain application layer. Maybe you are using more than one persistence technology and you want to wrap technology specific exceptions into a common base exception. In such situations, one can end with code like this:

public class MyRepository {
 	public Object getSomeData() { 
 		try {
 			// assume hibernate is used to access some data
 		} catch(HibernateException e) {
 			// wrap hibernate specific exception into a general DataAccessException
 			throw new DataAccessException(e);
 		}
 	}
}

Of course this becomes ugly if you have to do this every time you access a certain framework.
The AspectJ way
AspectJ is an aspect oriented programming (AOP) extension for Java. With AspectJ we can define Cross-cutting concerns that take care of the exception translation process for us.

To get started we first have to add the AspectJ dependency to our project:

<dependency>
 	<groupId>org.aspectj</groupId>
 	<artifactId>aspectjrt</artifactId>
 	<version>1.7.4</version>
</dependency>

Next we have to set up ajc, the compiler and bytecode weaver for AspectJ. This step depends on the developing environment you are using, so I will not go into details here. Eclipse users should have a look at theAspectJ Development Tools (AJDT) for Eclipse. IntelliJ IDEA users should make sure the AspectJ plugin is enabled. There is also an AspectJ Maven plugin available (check this pom.xml for an example configuration).

Now let's define our aspect using AspectJ annotations:

@Aspect
public class ExceptionTranslationAspect {

 	@Around("execution(* com.mscharhag.exceptiontranslation.repository..*(..))")
 	public Object translateToDataAccessException(ProceedingJoinPoint pjp) throws Throwable {
 		try {
 			return pjp.proceed();
 		} catch (HibernateException e) {
 			throw new DataAccessException(e);
 		}
 	}
}

Using the @Aspect annotation we can declare a new aspect. Within this aspect we use the @Aroundannotation to define an advice that is always executed if the passed pointcut is matched. Here, the pointcut

execution(* com.mscharhag.exceptiontranslation.repository..*(..))

tells AspectJ to call translateToDataAccessException() every time a method of a class inside thecom.mscharhag.exceptiontranslation.repository package is executed.
Within translateToDataAccessException() we can use the passed ProceedingJoinPoint object to proceed the method execution we intercepted. In this example we just add a try/catch block around the method execution. Using the ProceedingJoinPoint instance we could also do more interesting things like analyzing the method signature using pjp.getSignature() or accessing method parameters withpjp.getArgs().

We can now remove the try/catch block from the example repository implementation shown above and use a simple test to verify our aspect is working:

public class MyRepositoryTest {

 	private MyRepository repository = new MyRepository();

 	@Test(expected = DataAccessException.class)
 	public void testExceptionTranslation() {
 		this.repository.getSomeData();
 	}
}


Conclusion
Using AspectJ we can easily automate the conversion of Java runtime exceptions. This simplifies our code by removing try/catch blocks that would otherwise be required for exception translation.

You can find the full source of the example project on GitHub.

AspectJ Java (programming language) Translation intellij

Published at DZone with permission of Michael Scharhag. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Setting Up a Local Development Environment With IntelliJ, DevContainers, and Amazon Linux 2023
  • IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot
  • How To Approach Dependency Management in Java [Video]
  • NullPointerException in Java: Causes and Ways to Avoid It

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook