How to do exception Handling in Spring for REST Api?

Exception Handling is an integral part of any application and a good design for exception handling can give a better experience to the users. It makes your application very interactive. Spring provides an efficient framework for exception handling which makes it centralized and easy to use.

Disadvantage with previous approach

  1. No separation of concern: There was no separate handling of exception. It makes code dirty and difficult to maintain. There should be some mechanism wherein if application throws some exception to indicate some failure, it should be handled separately.
  2. Scattered Coding: The exception handling code was all scattered in the application along with other code and it results in duplicate coding.

Spring Exception Handling Solution

To resolve the above issues and to provide a centralized solution throughout the whole application, Spring provides a framework for exception handling. Lets see how it works.

@ControllerAdvice

This annotation can be used with any class to make it a global exception handler. When we use this annotation with any class, we can define all our exceptions in that class and provide implementation to handle those exceptions. Whenever any exception is thrown from application, the control will directed to the corresponding exception handler method in @ControllerAdvice class. An example will make the above explaination clear.

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler 
{
    @ExceptionHandler(FileNotFoundException.class)
    public final ResponseEntity<ErrorResponse> handleFileNotFoundException(FileNotFoundException ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("File Not Found", details);
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
 
    @ExceptionHandler(RecordNotFoundException.class)
    public final ResponseEntity<ErrorResponse> handleUserNotFoundException(RecordNotFoundException ex,
                                                WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new 
        ErrorResponse("Record Not Found", details);
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }
}


		
		
			

Leave a Comment

Your email address will not be published. Required fields are marked *