Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best approach and practices to handle exceptions in Spring? [closed]

I have been developing a web app in Spring + hibernate for last few months. What I have been seriously missing is exception handling.

I want to know the best approaches and Practices to handle exception? I have some questions in my mind which could not be covering all aspects of exception handling like:

1.Whether to make checked or unchecked Exception?How to decide?

2.How to handle and what to do with the exceptions generated in the Controller.

3.What about exceptions which are generated in Service layer and DAO layer?should they be handled in that layer only or should it be transferred to controller layer?

4.Since there are could be numerous exceptions,how could I be prepared to handle those which could come in future?

5.How can I display relevant messages to UI or browser?

Please suggest or provide links to good blogs?

like image 287
beinghuman Avatar asked Aug 29 '13 11:08

beinghuman


1 Answers

  1. Use Checked Exceptions if there is a reasonable expectation that the client can handle and recover from the exception otherwise use Unchecked (you will mostly use unchecked).
  2. Use the @ExceptionHandler annotation on a method to handle exceptions generated from @RequestMapping methods.
  3. throw them to the controller so it can decide the best response, unless the service method can actually recover from the exception and proceed with processing as normal.
  4. Create custom exceptions and throw those instead (you can pass the actual exception as the cause ie throw new MyCustomException("my message", e))
  5. Your @ExceptionHandler method can decide what view to return to the user, or you can configure a custom error page in your web.xml
like image 80
jax Avatar answered Sep 28 '22 20:09

jax