Custom Exception Handling For Spring Boot Rest Controller

There can be a scenario where we want to send a custom success or error message as a response to the Rest API call.

This can be easily achievable using @ControllerAdvice annotation by implementing Custom Exception Handler. It can be either global error message or controller level messages. Here I am going to explain how to implement a global exception handler in spring boot.


Below are the steps to implement custom error response in Spring boot Rest Controller 

  1.  Implement a custom exception handler by extending ResponseEntityExceptionHandler with @ControllerAdvice annotation.
  2. Implement a Custom Exception. 
  3. Design a CustomApiException Response Model.
  4. Throw custom exception from Rest Service.

Step 1 - Implementing a Custom Exception Handler

When implementing a custom exception handler either you can implement a custom method to handle the exception or override the default "handleException" method 

Example to implement a custom exception handler method 
Below exception handler method "handleNoProductsFoundException" handles  "NoProductFoundException" which is the custom exception I am going to create in Step 2 
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(NoProductFoundException.class)
public final ResponseEntity<ApiExceptionResponse> handleNoProductsFoundException(NoProductFoundException ex, WebRequest request) {
ApiExceptionResponse apiExceptionResponse = new ApiExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<>(apiExceptionResponse, HttpStatus.NOT_FOUND);

}

}

Step 2 -  Implementing custom exception 

Custom Exception should be created by extending "RuntimeException"

public class NoProductFoundException extends RuntimeException {
public NoProductFoundException(String exception) {
super(exception);
}
}

Step 3 - Custom API Exception Model 

Design a custom API exception response model with the properties whichever need to be returned like error message, date and time etc...

import java.util.Date;

public class ApiExceptionResponse {
private Date timestamp;
private String message;
private String details;

public ApiExceptionResponse(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}

public Date getTimestamp() {
return timestamp;
}

public String getMessage() {
return message;
}

public String getDetails() {
return details;
}
}

Step 4 - Throw Custom Exception From Rest Service

Throw the custom exception implemented from Rest Service where ever needed using "throw new".
@Service
public class ProductService {

@Autowired
ProductRepository productRepository;


public List<Product> getAllProduct() {
List<Product> products = productRepository.findAll();
if (products.isEmpty()) {
throw new NoProductFoundException("No products available");
}
return products;

}

public Product createProduct(Product product) {
return productRepository.save(product);
}
}

and that's it, we have implemented a global custom exception handler for the rest controller.
Complete source code for this example available at Git

Comments

Popular posts from this blog

Create MultiSelect Dropdown using vue-multiselect

Get rid of boring for loop and try using "range" and "rangeClosed"