Spring boot custom exception handling

What you will learn here about exception handing in spring boot

  • Spring boot custom exception handling

How to handle custom exception in spring boot is one the common java interview question. So here we are going to see how to handle custom exception in spring boot. Please click on following to download Custom exception handing in Spring boot sample project code.

Download Custom Exception sample project code (701 downloads)

Spring boot custom exception handling

Please follow the following steps to know how to handle custom exception in spring boot

1)Create package and create classes which is shown below

  1. First create package which is shown in step 1
  2.  Now create class for defining custom error response which is defined in step 2
  3. Create class which extends RuntimeException to define custom  exception which is shown in step 3

 

Define custom response for custom exception

2)Create rest controller and define exception handler

  1. Create new package for Rest controllers which is shown in step 1
  2. Define request Handler for respective URL which is shown in step 2
  3. Handle Custom exception using @ExceptionHandler which is shown in step3
  4. Step 4 will handle any kind of exception

 

Spring boot custom exception handling

3)Run your spring boot application which is shown below
Run spring boot application

4)Now open browser and make Get request to respective URL with valid user id. I have made request for user 10 which is shown below. Any number between 0  and 100 is valid user other numbers are invalid users.
valid user

5)Here I have entered user id as 200 which is invalid user because of this we are getting custom response for custom exception. Please check step 2.3
invalid user

6)Here I have entered user id as 200jj which is invalid user because of this we are getting custom response for custom exception. Please check step 2.4
invalid data

You may also like...