Back to: Spring Boot Tutorials
Spring Boot Exception Handling
In this article, I am going to discuss Spring Boot Exception Handling with Examples. Please read our previous article where we discussed Spring Boot RESTful Web Services.
What is Exception Handling?
The Exception is an abnormal condition that occurs during run time, which disturbs the normal flow of a program. Exception handling is a mechanism to handle such run-time errors. Some examples are ClassNotFoundException, IOException, SQLException, RemoteException, NullPointerException, ArithmeticException, etc.
In exception handling, we anticipate all possible errors by keeping a ‘lookout’ for them. We then write code that needs to be executed when such errors occur.
Exception Handling in Spring Boot
When an exception occurs, the program ‘throws’ an error, which then needs to be ‘caught’ and handled. We can either use inbuilt exceptions (such as RuntimeException) or define our own exceptions. In this article, we shall be defining and using our own exceptions. We will be using the project we used in the previous article (Link here: RESTful API). We shall use two annotations as below:
- @ControllerAdvice – This annotation allows for exceptions to be handled globally. This means that an exception thrown from one class can be caught in another class.
- @ExceptionHandler – This annotation is responsible for handling specific exceptions. When an exception occurs, messages are sent to the client
We will create two more classes, one defining the exception and another handling the exception. Follow the steps below:
Step 1: Create a class defining the exception. To do this, create a new file called FruitNotFoundException.java in the src/main/java/com/dotnet/restful folder.
Step 2: Each class that defines an exception must inherit from another exception. This makes it such that an object of this class can be thrown. In this case, we shall use RuntimeException.
Step 3: Create a class defining the exception. To do this, create a new file called FruitExceptionController.java in the src/main/java/com/dotnet/restful folder.
Step 4: Import the following packages into FruitExceptionController.java:
Step 5: Modify the code in FruitExceptionController.java to:
We have performed the following modifications:
- Added the @ControllerAdvice annotation
- Added the @ExceptionHandler annotation and map it to FruitNotFoundException
- Wrote code to handle the FruitNotFoundException. We will send a message to the client stating that the fruit was not found, along with a NOT FOUND HTTP message.
Step 6: Modify the FruitServiceController.java class to throw the exception when the fruit is not found. We can throw this exception from the DELETE and PUT requests.
Step 7: Execute the application. Verify that it starts properly.
Step 8: Open Postman and send a GET request to the server. This is to ensure that the server is running and that the application is functioning properly.
As can be seen above, the application is functioning properly. There are currently 4 fruits with ids 1, 2, 3, and 4. If we enter a PUT or DELETE request with id = 5, the FruitNotFoundEception must be raised, and we must receive a message stating “Fruit not found!” in Postman.
As can be seen above, the expected message was received. Also, the correct status code (404 not found) was also received.
The Complete Example Code
Fruits.java – The POJO Class
package com.dotnet.restful; public class Fruits { private String id; private String name; public String getId() {return id;} public void setId(String id) {this.id = id;} public String getName() {return name;} public void setName(String name) {this.name = name;} public Fruits (String nid, String nname) { id = nid; name = nname; } }
FruitServiceController.java – The class providing the RESTful services
package com.dotnet.restful; //Map classes import java.util.HashMap; import java.util.Map; //Required web classes import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class FruitServiceController { private static Map<String, Fruits> productRepo = new HashMap<>(); static { Fruits apple = new Fruits("1","Apple"); productRepo.put(apple.getId(), apple); Fruits banana = new Fruits("2","Banana"); productRepo.put(banana.getId(), banana); Fruits chiku = new Fruits("3","Chiku"); productRepo.put(chiku.getId(), chiku); Fruits dragon = new Fruits("4","Dragon Fruit"); productRepo.put(dragon.getId(), dragon); } @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { if (!productRepo.containsKey(id)) throw new FruitNotFoundException(); productRepo.remove(id); return new ResponseEntity<>("Fruit is deleted!", HttpStatus.OK); } @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Fruits product) { if (!productRepo.containsKey(id)) throw new FruitNotFoundException(); productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Fruit is updated!", HttpStatus.OK); } @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Fruits product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Fruit is created!", HttpStatus.CREATED); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }
FruitNotFoundException.java – The class defining the exception
package com.dotnet.restful; public class FruitNotFoundException extends RuntimeException { }
FruitExceptionController.java – The exception controller class
package com.dotnet.restful; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class FruitExceptionController { @ExceptionHandler(value = FruitNotFoundException.class) public ResponseEntity<Object> exception (FruitNotFoundException e) { return new ResponseEntity<>("Fruit not found!", HttpStatus.NOT_FOUND); } }
RestfulApplication.java – The application containing the main() function
package com.dotnet.restful; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestfulApplication { public static void main(String[] args) { SpringApplication.run(RestfulApplication.class, args); } }
In the next article, I am going to discuss Spring Boot Interceptor. Here, in this article, I try to explain Spring Boot Exception Handling with Examples. I hope you enjoy this Spring Boot Exception Handling article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.