In complex microservices, advanced error handling goes beyond simple exception logging. Effective error handling is crucial for reliability, scalability, and maintaining good user experience. This article will cover advanced techniques for error handling in Spring Boot microservices, focusing on strategies for managing errors in distributed systems, handling retries, creating custom error responses, and logging errors in a way that facilitates debugging.
Let’s start with a foundational error handling approach in Spring Boot to set up a baseline.
Spring Boot provides a global exception handler with @ControllerAdvice and @ExceptionHandler. This setup lets us handle exceptions across all controllers in one place.
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) { ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) { ErrorResponse error = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred."); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } }
Here, ErrorResponse is a custom error model:
public class ErrorResponse { private String code; private String message; // Constructors, Getters, and Setters }
Ensuring all exceptions return a consistent error response format (e.g., ErrorResponse) helps clients interpret errors correctly.
Assigning a unique error ID to each exception helps track specific errors across services. This ID can also be logged alongside exception details for easier debugging.
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) { String errorId = UUID.randomUUID().toString(); log.error("Error ID: {}, Message: {}", errorId, ex.getMessage(), ex); ErrorResponse error = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred. Reference ID: " + errorId); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); }
Clients receive an error response containing errorId, which they can report back to support, linking them directly to the detailed logs.
In distributed systems, transient issues (like network timeouts) can be resolved with a retry. Use Spring’s @Retryable for retry logic on service methods.
First, add Spring Retry dependency in your pom.xml:
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
Then, enable Spring Retry with @EnableRetry and annotate methods that need retries.
@EnableRetry @Service public class ExternalService { @Retryable( value = { ResourceAccessException.class }, maxAttempts = 3, backoff = @Backoff(delay = 2000)) public String callExternalService() throws ResourceAccessException { // Code that calls an external service } @Recover public String recover(ResourceAccessException e) { log.error("External service call failed after retries.", e); return "Fallback response due to error."; } }
This configuration retries the method up to 3 times, with a delay of 2 seconds between attempts. If all attempts fail, the recover method executes as a fallback.
For error handling in service-to-service calls, Feign provides a declarative way to set up retries and fallbacks.
Define a Feign client with fallback support:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) { ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) { ErrorResponse error = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred."); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } }
This approach ensures that if inventory-service is unavailable, the InventoryServiceFallback kicks in with a predefined response.
Configure an ELK (Elasticsearch, Logstash, Kibana) stack to consolidate logs from multiple microservices. With a centralized logging system, you can easily trace issues across services and view logs with associated error IDs.
For example, configure log patterns in application.yml:
public class ErrorResponse { private String code; private String message; // Constructors, Getters, and Setters }
In distributed systems, tracing a single transaction across multiple services is critical. Spring Cloud Sleuth provides distributed tracing with unique trace and span IDs.
Add Spring Cloud Sleuth in your dependencies:
@ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) { String errorId = UUID.randomUUID().toString(); log.error("Error ID: {}, Message: {}", errorId, ex.getMessage(), ex); ErrorResponse error = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred. Reference ID: " + errorId); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); }
Define custom exceptions to provide more specific error handling.
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
Customize error responses by implementing ErrorAttributes for structured and enriched error messages.
@EnableRetry @Service public class ExternalService { @Retryable( value = { ResourceAccessException.class }, maxAttempts = 3, backoff = @Backoff(delay = 2000)) public String callExternalService() throws ResourceAccessException { // Code that calls an external service } @Recover public String recover(ResourceAccessException e) { log.error("External service call failed after retries.", e); return "Fallback response due to error."; } }
Register CustomErrorAttributes in your configuration to automatically customize all error responses.
Use the Problem Details format for a standardized API error structure. Define an error response model based on RFC 7807:
@FeignClient(name = "inventory-service", fallback = InventoryServiceFallback.class) public interface InventoryServiceClient { @GetMapping("/api/inventory/{id}") InventoryResponse getInventory(@PathVariable("id") Long id); } @Component public class InventoryServiceFallback implements InventoryServiceClient { @Override public InventoryResponse getInventory(Long id) { // Fallback logic, like returning cached data or an error response return new InventoryResponse(id, "N/A", "Fallback inventory"); } }
Then, return this structured response from the @ControllerAdvice methods to maintain a consistent error structure across all APIs.
logging: pattern: console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
Integrating a circuit breaker pattern protects your microservice from repeatedly calling a failing service.
Using Resilience4j Circuit Breaker
Add Resilience4j to your dependencies:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency>
Then, wrap a method with a circuit breaker:
public class InvalidRequestException extends RuntimeException { public InvalidRequestException(String message) { super(message); } }
This setup stops calling getInventory if it fails multiple times, and inventoryFallback returns a safe response instead.
Advanced error handling in Spring Boot microservices includes:
Centralized error handling for consistent responses and simplified debugging.
Retries and circuit breakers for resilient service-to-service calls.
Centralized logging and traceability with tools like ELK and Sleuth.
Custom error formats with Problem Details and structured error responses.
These techniques help ensure your microservices are robust, providing consistent, traceable error responses while preventing cascading failures across services.
The above is the detailed content of Advanced Error Handling in Spring Boot Microservices. For more information, please follow other related articles on the PHP Chinese website!