How do you handle exceptions globally in Spring Boot?

In Spring Boot, global exception handling can be done using @ControllerAdvice and @ExceptionHandler annotations. This allows you to centralize exception handling for all controllers, ensuring consistency and reducing duplicate code in your application.

Steps to Handle Exceptions Globally:

1. Create a Global Exception Handler Class:

  • Create a class annotated with @ControllerAdvice. This class will contain methods to handle specific exceptions globally across your application.

2. Use @ExceptionHandler for Specific Exceptions:

  • Inside the @ControllerAdvice class, use @ExceptionHandler to specify which exception types each method should handle. This ensures that when the exception occurs, the corresponding method will be invoked to handle it.

3. Return Custom Error Response:

  • Each exception handler method can return a custom error response (such as a custom JSON object or a specific HTTP status) using ResponseEntity.

Example: Global Exception Handling in Spring Boot

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
// Custom exception class  

class ResourceNotFoundException extends RuntimeException {

public ResourceNotFoundException(String message) {

super(message);

}

}

// Global exception handler class

@ControllerAdvice

public class GlobalExceptionHandler {

// Handle specific exception (e.g., ResourceNotFoundException)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
String errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.NOT_FOUND);
}

// Handle global exceptions (e.g., all unhandled exceptions)
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
String errorMessage = "An unexpected error occurred: " + ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
}


}  

Explanation:

  1. Custom Exception:
  2. ResourceNotFoundException is a custom exception that you can throw when a resource (like a user or product) is not found in the database.
  3. Global Exception Handler:
  4. The GlobalExceptionHandler class is annotated with @ControllerAdvice, which makes it applicable globally to all controllers in the application.
  5. The handleResourceNotFoundException method handles exceptions of type ResourceNotFoundException and returns a NOT_FOUND HTTP status (404).
  6. The handleGlobalException method catches all other exceptions and returns a generic INTERNAL_SERVER_ERROR (500) status.

Benefits of Global Exception Handling:

  • Consistency: Ensures that all exceptions are handled uniformly.
  • Reusability: Centralizes exception handling, avoiding repeated code in controllers.
  • Customization: You can customize error messages and response formats (JSON/XML) for different exceptions.