Exception Translation in Java vs. Scala

Exception Translation is a very important pattern to prevent your code from being cluttered by framework specific exception types. For example, you don’t want to deal with JDBC exceptions in your business code, especially because you might want to switch to JPA or a NoSQL database some day.
The idea is to translate all vendor specific exceptions to an internal exception hierarchy before they cross layer or module boundaries. So, a developer of an higher level module has only to deal with a known set of possible exceptions and will not get headaches because of cryptic database exceptions.
Since Exception Translation is a cross cutting concern it should not be done in the production code. Lower level modules should not even know about the exception hierarchy used up the call stack by higher level modules.

Let’s say we have an persistence layer with repositories that throw all kinds of javax.persistence Exceptions and a service layer that only want to deal with internal exceptions:

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {
  @PersistenceContext
  private EntityManager entityManager;

  public Customer persist(Customer customer) {
     //Could throw an javax.persistence.OptimisticLockException
     return this.entityManager.merge(partner);
  }  
}
   //In the service code
   try {
      this.customerRepository.persist(customer);
   } catch (my.ConcurrentUpdateException e) {
     //Deal with it
   }

In Java the only way to do such a translation is AOP. In Spring you could do something like this:

public class ExceptionTranslator {

  public void handleException(Throwable ex) {
    if (ex instanceof javax.persistence.OptimisticLockException) {
      return new my.ConcurrentUpdateException(
        "Concurrent update", ex);
    }
    //more
  }
}
<bean id="exceptionTranslator" class="my.ExceptionTranslator"/>

<aop:config>
  <aop:aspect ref="exceptionTranslator">
    <aop:pointcut id="repositoryMethod" 
       expression="within( @org.springframework.stereotype.Repository *)" />
    <aop:after-throwing pointcut-ref="repositoryMethod" 
       method="handleException" throwing="ex"/>
  </aop:aspect>
</aop:config>

This approach is of course quite magic (as AOP always is) and might be confusing to developers. Because they throw an exception on one end and have to catch another one at the other.

In Scala is is possible to integrate the exception translation directly in the code, but do the actual translation at one place at the same time. Due to the magic of closures and lazy evaluation. Remember, in Scala you can defer the evaluation of an method argument with the “=>” operator.

So, we could do this:

def persist(customer: Customer): Customer = {
  translateExceptions {
    this.customerRepository.persist(customer)
  }
}

If the translateExceptions Method looks like this:

def translateExceptions[T <: Any](body: => T): T = {
  try {
    body //Evaluate the given method body
  } catch {
    case e: javax.persistence.OptimisticLockException 
      => throw new my.ConcurrentUpdateException("Concurrent udpate", e)
  }
}

You could put the translation method into a Scala object and use it from everywhere:


object ExceptionTranslator {
  def apply[T <: Any](body: => T): T = {
  try {
    body
  } catch {
    case e: javax.persistence.OptimisticLockException 
      => throw new my.ConcurrentUpdateException("Concurrent udpate", e)
  }
}

//And use it like this:
def persist(customer: Customer): Customer = {
  ExceptionTranslator {
    this.customerRepository.persist(customer)
  }
}

Much smarter, much more understandable as in Java.

Obtain the runtime class of a type parameter in Scala

One of the most questionable features of the Java runtime is for certain type erasure. It renders type parameters a mere compiler feature with no benefits at runtime.

Scala basically suffers from the same problem, by default the compiler strips away all type information from parametrized types. But fortunately there is a simple way to request the compiler to generate some meta information which can be obtained at runtime: Just add the predefined type Manifest as context bound to the type parameter like this:

class Test[A : Manifest]

The runtime class can then be obtained like this:

val runtimeClass = manifest[A].runtimeClass

You can see a context bound as a has a relation of the type parameter. In fact it’s a shorthand for an implicit constructor argument. One could also have written:

class Test[A](implicit m: Manifest[A]) 

But that’s not so handy if more than one type parameter is involved.

Below a full example how the runtime class could be used in a base class for a CRUD repository:

abstract class CRUDRepository[E <: Serializable](implicit m: Manifest[E]){

  val runtimeClass = m.runtimeClass
  println(s"Runtime class: $runtimeClass")

  @PersistenceContext 
  @BeanProperty
  var entityManager: EntityManager = _

  def findById(id: long) = this.entityManager.find(
    runtimeClass, id)

  def findAll() = this.entityManager.createQuery(
    s"from ${runtimeClass.getName}").getResultList()

  def persist(entity: A) = this.persist(entity)

  //...

}

case class Person(name: String)

@Repository
class PersonRepository extends CRUDRepository[Person]

Please note, that context bounds do not work with Traits, since they cannot have constructors.

Real delegation in Scala

Surprisingly, most programming languages don’t support the actual Delegation concept, which means dynamically extending an object and is supposed to be an alternative for static inheritance. The key difference to simple message forwarding (as in the GOF Delegation pattern) is, that within a delegatee method this (or self) always points to the delegator object. So, the delegatee is not an actual object but more a plug-in, the programming language Self consequently refers to it as Slots.

In Scala we can simulate this idea of delegation by using traits with a explicitly typed self reference. The type of the self reference must of course match the delegator class:

  trait Delegatee { this: Delegator =>
    println(this.publicMethodOfTheDelegator)
  }

The only drawback is, that we can only access public members of the delegator here.

Below a real world example: We extend the java.awt.Rectangle class by some calculation methods. But without doing what extending usually means, which is creating a subclass:

object DelegationTest extends App {

  trait RectangleCalculations { this: java.awt.Rectangle =>
    def area = getWidth * getHeight
  }

  val rect = new java.awt.Rectangle(10, 20) 
                    with RectangleCalculations

  println(rect.area)
}