For example: we have WebApplication based on MVC. Also, for this app we are used: Spring, Struts 2 and Hibernate frameworks.
Lets go look on small scenario: user try save some instanse, for example: BO Book.
So, user fill form fields and send request to the server:
What happened on server?
- Execute action method
Action.Save(); - Inside
Action.Save()callService.save(); - Inside
Service.save()callDaoHibernate.save(); - Inside
DaoHibernate.save()callgetHibernateTemplate().save();
Method getHibernateTemplate.save() – it is framework implementation, so we cant access to this method. We only know, that if something fail inside this method throws DataAccessException.
So, at this moment I think, how correct implement my logging and error handling?
On which level?
On Dao level? Service level?
Or on level Struts actions?
What do you think about this?
Or need on each level?
What best practices you can recommended?
Here is your architecture:
How do you want to handle the error on DAO layer? Return fake data? Empty collection? if you can’t, just let the exception pop-up.
And how about handling on the service layer? You know that the database is not working, so what can you return to the Struts action? An empty result? An error object? Isn’t exception an error object?
So the exception appears in the Struts action. Here you have some options. If the exception will actually tell something to the user and your GUI is prepared, you can return different view (and log the exception here).
But what if you catch a
NullPointerExceptionin Struts action? Will you handle it separately in every Struts action? No, so pass the exception even further (!)I think you get the idea – as long as you don’t know how to handle the exception (and logging is not handling), let the client clean-up the mess. Otherwise you are only hiding the problem and increasing the damages (e.g. transactions aren’t rolled-back, users see incorrect results).
I would advice implementing generic exception handling mechanism which logs the exception and returns HTTP 500 to the user. Gentle error message (without stack trace) should appear and the user should be apologized. You should investigate every error that reaches this layer.
As far as I remember Struts (and virtually every web framework) has some centralized way of handling exceptions. (Struts 2 Exception Handling Docs)