Member-only story
Spring Boot Global exception handling
In this article, we’ll take a look at how to create a global exception handler. We’ll also create a custom exception. With a global exception handler, we’ll be able to throw Custom exceptions for different business logic with custom messages for each, and the global exception handler will handle them and return the appropriate response to the user.
We’ll be continuing with the code from the previous article where we added validation to the requests.
Custom Exception
We’ll create a new exception class that extends the RuntimeException class. We can also extend just “Exception” but that would mean we’ll have to add “throws …” to places we throw this custom exception. Since “RuntimeException” is unchecked, we don’t have to do that.

Throwing Exception
We’ve created a service class where we can add all business logic. If anything goes wrong ie a user is not found in the database, or data is not valid, we can throw our custom exception.

and the controller method looks like this.