Global Exception Handling Using Spring @RestControllerAdvice in REST Services
This article will try to cover global exception handling using ControllerAdvise annotation introduced in Spring 4.3.
Join the DZone community and get the full member experience.
Join For Free
A REST API developer will have two requirements related to error handling.
- Common place for Error handling
- Similar Error Response body with a proper HTTP status code across APIs
Both requirements can be addressed by using RestControllerAdvice annotation in Spring.
Refer to code at https://github.com/DharmendraRathor/springzone/tree/master/customer.
I have created Get customer service for customer resource.
"/customer") (
public class CustomerController {
private CustomerManager customerManager;
"/{id}") (
public Customer getCustomer( String id) {
return customerManager.getCustomer(id).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));
}
}
curl --request GET --url http://localhost:8080/customer/1
xxxxxxxxxx
If customer does not exist in DB , I want to throw error message with http Status 404.
{
"errorCode": "NOT_FOUND_ERROR",
"errorMsg": "Customer not found with id 1",
"status": 404,
"timestamp": "2019-12-26 11:45:59"
}
To achieve this, we have to define global exception handler class with annotation @RestControllerAdvice.
You may also be interested in: Global Exception Handling With @ControllerAdvice
We have added one method "handleGenericNotFoundException", which handles exceptions defined with
@ExceptionHandler(value = NotFoundException.class).
Any service generating exception "NotFoundException" will come to “handleGenericNotFoundException” method, and the method will wrap the exception in common format using the "CustomErrorResponse" class. In this case, the "customer not found" error will be thrown as defined in “handleGenericNotFoundException” method inside the ExceptionAdvice class.
xxxxxxxxxx
public class ExceptionAdvice {
value = NotFoundException.class) (
public ResponseEntity<CustomErrorResponse> handleGenericNotFoundException(NotFoundException e) {
CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR", e.getMessage());
error.setTimestamp(LocalDateTime.now());
error.setStatus((HttpStatus.NOT_FOUND.value()));
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
CustomErrorResponse can be found at CustomErrorResponse.
We can define multiple error handler methods for different types of exceptions generated by services in "ExceptionAdvice" class and wrap each using common CustomErrorResponse response. This will make sure we have common place to handle errors and all services return similar error responses.
The git repo for the complete project git project.
Further Reading
Spring REST Service Exception Handling
Opinions expressed by DZone contributors are their own.
Comments