Exception translation in java

Java: Exception Translation with AspectJ

Join the DZone community and get the full member experience.

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:

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.

Читайте также:  Потоки ввода вывода kotlin

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

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

Opinions expressed by DZone contributors are their own.

Источник

Exception Translation with ET

Some time ago I wrote a small blog post about exception translation with AspectJ. In this blog post we will see how to accomplish the same using ET and its lighter Java 8 approach.

Motivation

Exception translation (or exception conversion) is the process of converting one type of exception into another. The Java code to translate an exception is quite simple and I think every Java developer writes something like this from time to time:

Exception translation is typically applied if exceptions from third party libraries do not fit into your application. Reasons for this might be:

  • Exceptions thrown by a library are too low level and/or you do not want to leak implementation details into other parts of your application. For example, you want to use a more generic DataAccessException instead of a lower level SQLException .
  • A library is using checked exception while you prefer using only runtime exception in your application.

Exception Translation with ET

ET is a small and simple library for exception translation. To get started with ET, you just need to add the following dependency to your code:

ET makes use of Java 8 features, so do not forget to set your compiler Level to Java 8.

We start with configuring an ExceptionTranslator instance:

ExceptionTranslator et = ET.newConfiguration() .translate(IOException.class).to(MyRuntimeException.class) .translate(FooException.class, BarException.class).to(BazException.class) .done()

Here we create an ExceptionTranslator that converts IOException , FooException and BarException . IOException will be translated to MyRuntimeException while FooException and BarException are translated to BazException .

Please note that ET requires the translation target exceptions (here MyRuntimeException and BazException ) to be RuntimeExceptions .
ExceptionTranslator instances are thread safe and immutable. It is safe to configure an ExceptionTranslator once and then make it globally available.

Now we can use our new ExceptionTranslator to wrap the code that can throw exceptions we want to convert.

If now an IOException is thrown by dangerOperation() et will catch it. et then throws a new MyRuntimeException from the caught IOException . The original IOException is stored in the cause field of MyRuntimeException .

To return a value from a translation block withReturningTranslation() can be used:

MyResultClass data = et.withReturningTranslation(() -> < . return myObject.dangerOperation(); >);

Summary

ET is a small library that might be useful to you, if you have to do a lot of exception conversion in your code. After configuring your conversion rules once, exceptions can be converted by simply wrapping the code in a lambda expression.

Читайте также:  Python package for gui

Have a look at the full ET documentation on GitHub.

Источник

Java: Exception translation with AspectJ

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); >> >

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:

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 the AspectJ 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 @Around annotation 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 the com.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 with pjp.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

Источник

Java: Exception translation with AspectJ

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

Читайте также:  Clear all cache php

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:

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 the AspectJ 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 @Around annotation 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 the com.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 with pjp.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.

Источник

Оцените статью