Spring boot global exception handler
What you will learn here about Spring boot exception handling
- Why we need global exception handler in spring boot
- Spring boot global exception handler
Why we need global exception handler in spring boot
In Spring rest controller generally we write our exception handler which is responsible for handling exception thrown by that particular rest controller only which is shown below.
Spring boot custom exception handling
In real time project we can have multiple rest controllers and we need to handle exception thrown by those rest controllers. So instead of handing exception in each rest controller, we will have common exception handler for all rest controller which will help us to avoid code redundancy.
Please click on below link to download sample project
Download Global exception handler sample project (256 downloads)
Spring boot global exception handler
Please follow the following steps to know how to handle exception in spring boot using global exception handler.
1)Create package and define custom exception and response message which is shown below
- First create package under your project which is shown below in step 1
- Create new class and define custom response which is shown below in step 2
- Create new class and define custom exception which is shown below in step 3
2)Create new package and define rest controller
- First create new package which is shown in step 1
- create new class and define rest controller which is shown in step 2
3)Create Global exception handler
- First create new package
- Define global exception handler using @ControllerAdvice which is shown below in step 2
4)Run the spring boot application
5)Open the browser and make valid user request using respective URL which is shown below
6)Open the browser and make invalid user request using respective URL which is shown below
7)Open the browser and make wrong user request using respective URL which is shown below