Where to handle Exceptions in Spring Applications

Viewed 9833

I'm still learning Spring. I have an Application set upped and i'm trying to understand exception handling in Spring.

I'm using @ControllerAdvice to handle exceptions. In my application there are few layers such as Services, Controllers, Models and Repositories. In which Layer should i be handling my exceptions? Or should i be handling exception in each layer as appropriate?

6 Answers

I think the accepted answer is nice. It uses Spring @ControllerAdvice for global exception handling, also the enum to combine the error code and HTTP status.

However, I disagree with the Exception factory part. The factory logs the exception and throws it out. This is not recommended in many articles like this and this. Of course, if you have no any exception translation like, it should be ok since the exception will be logged only once. But you just simply could not sure that the translation won't be needed in the future.

I would recommend do the logging with the @ControllerAdvice since this is the final destination for your application exception. This could make sure that every exception will be log once and had a good handle to present to the client.

Related