Where to contact spring DataAccessException

I am developing an application using Struts, Spring and Hibernate.

My DAO uses spring jdbc, and its entire method throws a DataAccessException (this has not been verified).

Where should I handle these exceptions? I know this is an unchecked exception, but I think I need to tell the user if there is a problem with the db or it connection.

I think I should throw a DataAccessException from my service class methods that will be checked by the controller. Is this a good practice?

I looked at samples from the spring package and did not find exception handling in the scope or scope of service. When leaving the dao scope, a DataAccessException is ignored.

Please suggest a good design for this question.

+7
source share
2 answers

The DataAccessException error is ignored after exiting the dao scope.

And this is good! Let it fly through the whole stack. Probably you have transactions at the service level - an exception will transparently lead to the rollback of an external transaction. Fine!

Now he will find his way to the controller. If you catch it in the Struts controller, you can, for example, return a different view. But most likely you do not want to handle the exception in every Struts action. Therefore, let the exception fly even further. At some point, Struts will catch this exception and try to handle it. Struts has several complex error handling mechanisms, you will find a lot of information about them. Typically, it will trigger some custom actions or error screen depending on the type of exception.

Finally, even if Struts cannot handle the exception, it will be returned to the container, with the result that HTTP 503 with the exception data will be returned.

As you can see, you can control exceptions at many levels, usually better.

+13
source

Throwing an exception is also an expensive operation. This is a good option, which catches the exception at the level of the service itself and, based on the exception, generates a response and sends it to the controller. When developing an application, the developer always better understood what type of exception he / she should deal with. So catching exceptions and translating them into the appropriate answer is a good option.

0
source

All Articles