Member-only story

Spring Boot Global exception handling

theoneamin
2 min readMay 27, 2022

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

theoneamin
theoneamin

No responses yet

Write a response