Updated April 4, 2023
Introduction to Spring Boot Exception Handling
The following article provides an outline for Spring Boot Exception Handling. In spring boot, we have a mechanism to handle the exceptions globally by the use of controller advice provided by the spring boot framework. We should properly handle the exception and error, if any, in the API because, by that, we can return a useful status code to the client when the request for a particular resource from the server, also; we may get several exceptions while performing any business logic so we should handle them properly.
We should try to give some useful message to the client from which they can understand because they cannot understand the technical issue. We have class-based annotation and method based annotation in spring boot two handle the exceptions in our application. Here in this tutorial, we will see how we can implement this on our spring boot application to get useful information and status code if an exception occurs.
Syntax of Spring Boot Exception Handling
In spring, we can handle them globally; we have to use the standard annotation provided by the spring boot framework.
@ControllerAdvice
public class Name_of_class {
}
As you can see, we can create one class and annotate it using @ControllerAdvice in spring boot.
Example:
@ControllerAdvice
public class MyExceptionnHandler {
// logic will go here .. //
}
As you can see in the above piece of syntax, we can now write and handle our custom exception for the application.
How does Exception Handling work in Spring Boot?
As now we already know that exception handling can be done globally in spring boot, means we can have one class which can handle all the exception of the application at one place. In spring boot, we have @ControllerAdvice, which is responsible for handling the exception globally in spring boot. Also, we have one more annotation, which we have not talked about since this far, which is @ExceptionHandler, this annotation is responsible for handling the particular exception, and we used this to send the response to the client.
Here we will see how we can use both of this to create the custom exception handler in spring-boot:
1. @ExceptionHandler
This annotation can be used to handle the exception at the controller level. By the use of it, we can annotate a method with this, and it will be responsible for handling the exception if it occurs at this controller only. So by the use of it, we have to write the same method on every controller; this is not globally for our while application; this is easy to use, implement and handle but not feasible.
Example:
public class DemoController{
@ExceptionHandler({ yourexceptionclass1.class, yourexceptionclass2.class , ...soon})
public void handleexception() {
// logic will go here ..//
}
}
As you can see in the above code, we have defined one method which is going to handle the exception for our application. Inside that handler annotation, we can pass our all the custom class that we have created. This seems simple but not good practice to handle the exception globally in the application.
2. @ControllerAdvice
Spring boot provides us controller advice which is responsible for handling the exception at a global level. We have to just use this annotation and create one class, which will handle the multiple customs create exception at one level only.
Below are some advantages of using this to handle the exception:
- By the use of it, we can easily set the response message and Http status code by the use of ResponseEntity.
- We can define any number of exception handlers in this class, which will be global and used anywhere.
We have seen two approaches, but then we will see steps to implement the second one because it is more flexible to use without repeating the same code.
Let’s see the implementation of the second approach.
a. We have to first create the spring boot application from scratch if you do not have one. Go to spring initializer and fill in the details as per your need.
b. Generate the zip and import the project into your favorite editor; now, let get started with the actual implementation.
c. Now, we have to create one controller advice which will contain all the exception handler at a single level for our application; for this, we have to have proper import statement and packages in place.
Below is the syntax for the controller advice class:
Example:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ControllerAdvice
public class EmployeeExceptionController {
@ExceptionHandler(value = EmployeeNotExixts.class)
public ResponseEntity<Object> exception(EmployeeNotExixts exception) {
return new ResponseEntity<>("Employee do notexists !!", HttpStatus.NOT_FOUND);
}
}
d. Now, we have to create our custom exception that we have defined above in the controller advice class, i.e. ‘EmployeeNotExixts’.
Below is the syntax for the custom exception class:
Example:
public class EmployeeNotExixts extends RuntimeException {
private static final long serialVersionUID = 1L;
}
This class should extend the RuntimeException in order to throw any unchecked exception from the application.
e. Now, we need one controller to test our exception handling in the spring boot application; for this, we will write one method which is going to find the employee from the database based on the id passed in URL.
Example:
@RestController
@CrossOrigin
@RequestMapping("/operations/")
public class ActionController {
@RequestMapping(value = "get/employee/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> getEmployee(@PathVariable("empid") Long empid) {
// db call to fetch the emp and check ..///
if(!empid)throw new EmployeeNotExixts();
// logic goes here if emp found ..//
return new ResponseEntity<>("Found", HttpStatus.OK);
}
}
Now here we are trying to fetch the employee based on the id; if not found, we will throw employee not found exception in return to the client with HTTP status code and response message as well.
f. Main class for spring boot application will be plain and simple like always.
Example:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.*;
@SpringBootApplication
public class EmployeeApplication {
public static void main(String[] args)
{
SpringApplication.run(EmployeeApplication.class, args);
}
}
Output:
Conclusion
As you can see, exception handling is very easy to implement in the spring boot framework because it provides us good support to make it global and used anywhere in the any controller whenever we want, without being repeat the code as well.
Recommended Articles
This is a guide to Spring Boot Exception Handling. Here we discuss the introduction and how exception handling works in spring boot? You may also have a look at the following articles to learn more –