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

Custom exception handing in spring boot
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.
global exception handler

 

Please click on below link to download sample project
Download Global exception handler sample project (773 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

  1. First create package under your project which is shown below in step 1
  2. Create new class and define custom response which is shown below in step 2
  3. Create new class and define custom exception which is shown below in step 3

 

2)Create new package and define rest controller

  1. First create new package which is shown in step 1
  2. create new class and define rest controller which is shown in step 2

Rest controller

3)Create Global exception handler

  1. First create new package
  2. Define global exception handler using @ControllerAdvice which is shown below in step 2

Controller advice spring boot

4)Run the spring boot application
Run spring boot

5)Open the browser and make valid user request using respective URL which is shown below
valid id

6)Open the browser and make invalid user request using respective URL which is shown below
invalid id

7)Open the browser and make wrong user request using respective URL which is shown below

invalid request

You may also like...