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 (196 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
- First create package which is shown in step 1
- Now create class for defining custom error response which is defined in step 2
- Create class which extends RuntimeException to define custom exception which is shown in step 3
2)Create rest controller and define exception handler
- Create new package for Rest controllers which is shown in step 1
- Define request Handler for respective URL which is shown in step 2
- Handle Custom exception using @ExceptionHandler which is shown in step3
- Step 4 will handle any kind of exception
3)Run your spring boot application which is shown below
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.
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
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