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.
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.
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.
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.
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.
You should use AOP, with or without Spring and do in your aspects this kind of work (like exception translation, transaction management, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With