Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you design a services layer that's not all try/catch blocks?

When designing a SpringMVC application the @ExceptionHandler annotation is at our disposal in the REST layer. This greatly de-clutters controller methods by offloading exception handling to a set of semi-generic handlers.

The basic architecture of our services is this:

[REST API] <==> [Application Services] <==> [Data Layer]

I'm of the belief that a REST layer controller should not be dealing directly with Data layer exceptions, instead it should be dealing with Application Service exceptions only.

However, that means all my Application Services methods basically have to look like this:

public DomainObject getSomeDomainObjectById(String id) {
   DomainObject retVal = null;
   try {
      myDomainDao.getSomeDomainObjectById(id);
   } catch (DataLayerExceptionOfSomeSort ex) {
      throw translateToAppropriateServiceException(ex);
   }
   //do some further processing
   return retVal;
}

To me, that's a lot of in-your-face exception handling, which I don't care for. How else could I solve this? Is there an easy way to achieve the same thing in the Application Services layer as there is in the Rest layer?

My first thought is AOP. I'm open to this providing it doesn't add a lot of cruft and is easy to configure.

like image 737
ThaDon Avatar asked Jul 21 '14 18:07

ThaDon


People also ask

How do you handle exceptions in DAO layer in spring?

Every layer should have however their specific exceptions as generic. for example, DAO layer may have custom exception handlers like DavaSavingException, IOException etc.. So the approach is throw exception from DAO to service layer and again throw it to UI layer and catch in UI specific classes.

Which layer should handle exceptions?

This approach consists of all layers of the API Project being capable of catching exceptions and sending again the exception to the upper layers. The Controller layer is where the Domain Exceptions will be treated.

Should you try catch every function?

It's not recommended nor economical to put try-catch in every function and block code. Instead, create a separate class for exception handling and log exceptions here, then show or handle these exceptions.

Should I wrap everything try catch?

No, it's actually a reasonable thing to do in some applications, so that you can detect, log, report, and potentially handle (but most likely just rethrow or terminate) exceptions that are not caught elsewhere in the code.


1 Answers

You should use AOP, with or without Spring and do in your aspects this kind of work (like exception translation, transaction management, etc).

like image 104
Mektoub Avatar answered Oct 04 '22 02:10

Mektoub