0% found this document useful (0 votes)
7 views14 pages

Advanced Error Handling in Spring Boot Microservices _ by Bishwa Poudel _ Oct, 2024 _ Medium - Copy

The article discusses advanced error handling techniques in Spring Boot microservices, emphasizing the importance of effective error management for reliability and user experience. It covers strategies such as centralized logging, retry logic for transient errors, custom error responses, and the use of circuit breakers to enhance resilience. Additionally, it highlights the use of tools like ELK for logging and Spring Cloud Sleuth for distributed tracing to improve observability and debugging capabilities.

Uploaded by

awsiotsudhakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

Advanced Error Handling in Spring Boot Microservices _ by Bishwa Poudel _ Oct, 2024 _ Medium - Copy

The article discusses advanced error handling techniques in Spring Boot microservices, emphasizing the importance of effective error management for reliability and user experience. It covers strategies such as centralized logging, retry logic for transient errors, custom error responses, and the use of circuit breakers to enhance resilience. Additionally, it highlights the use of tools like ELK for logging and Spring Cloud Sleuth for distributed tracing to improve observability and debugging capabilities.

Uploaded by

awsiotsudhakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Advanced Error Handling in Spring Boot


Microservices
Bishwa Poudel · Follow
5 min read · 6 days ago

Listen Share More

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.

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 1/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

1. Basic Error Handling in Spring Boot


Let’s start with a foundational error handling approach in Spring Boot to set up a
baseline.

1.1 Using @ControllerAdvice and @ExceptionHandler

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 {

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 2/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoun
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 un
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


}

1.2 Returning Consistent Error Responses


Ensuring all exceptions return a consistent error response format (e.g.,
ErrorResponse ) helps clients interpret errors correctly.

2. Advanced Techniques for Error Handling

2.1 Centralized Logging and Tracking with Error IDs


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();

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 3/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

log.error("Error ID: {}, Message: {}", errorId, ex.getMessage(), ex);

ErrorResponse error = new ErrorResponse("INTERNAL_SERVER_ERROR",


"An unexpected error occurred. Ref
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.

2.2 Adding Retry Logic for Transient Errors


In distributed systems, transient issues (like network timeouts) can be resolved with
a retry. Use Spring’s @Retryable for retry logic on service methods.

Setup
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.
Open in app

Search
@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);

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 4/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

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.

2.3 Using Feign Client with Fallback in Microservices


For error handling in service-to-service calls, Feign provides a declarative way to set
up retries and fallbacks.

Feign Configuration
Define a Feign client with fallback support:

@FeignClient(name = "inventory-service", fallback = InventoryServiceFallback.cl


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");
}
}

This approach ensures that if inventory-service is unavailable, the


InventoryServiceFallback kicks in with a predefined response.

3. Error Logging and Observability

3.1 Centralized Logging with ELK Stack

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 5/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

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 :

logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

3.2 Adding Trace IDs with Spring Cloud Sleuth


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:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

With Sleuth, each request generates trace IDs, which are automatically included in
logs, making it easier to track errors across service boundaries.

4. Custom Error Handling for REST APIs

4.1 Creating Custom Exception Classes


Define custom exceptions to provide more specific error handling.

public class InvalidRequestException extends RuntimeException {


public InvalidRequestException(String message) {
https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 6/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

super(message);
}
}

4.2 Custom Error Response Structure


Customize error responses by implementing ErrorAttributes for structured and
enriched error messages.

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

@Override
public Map<String, Object> getErrorAttributes(
WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webReque
errorAttributes.put("timestamp", LocalDateTime.now());
errorAttributes.put("customMessage", "An unexpected error occurred");
return errorAttributes;
}
}

Register CustomErrorAttributes in your configuration to automatically customize all


error responses.

4.3 API Error Response Standardization with Problem Details (RFC 7807)
Use the Problem Details format for a standardized API error structure. Define an
error response model based on RFC 7807:

public class ProblemDetailResponse {


private String type;
private String title;
private int status;
private String detail;
private String instance;

// Constructors, Getters, and Setters


}

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 7/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Then, return this structured response from the @ControllerAdvice methods to


maintain a consistent error structure across all APIs.

@ExceptionHandler(InvalidRequestException.class)
public ResponseEntity<ProblemDetailResponse> handleInvalidRequest(InvalidReques
ProblemDetailResponse error = new ProblemDetailResponse(
"https://example.com/errors/invalid-request",
"Invalid Request",
HttpStatus.BAD_REQUEST.value(),
ex.getMessage(),
UUID.randomUUID().toString()
);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}

5. Circuit Breakers for Resilience


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>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>

Then, wrap a method with a circuit breaker:

@CircuitBreaker(name = "inventoryService", fallbackMethod = "inventoryFallback"


public InventoryResponse getInventory(Long id) {
// Call to external service
}

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 8/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

public InventoryResponse inventoryFallback(Long id, Throwable ex) {


log.warn("Fallback due to error: {}", ex.getMessage());
return new InventoryResponse(id, "N/A", "Fallback inventory");
}

This setup stops calling getInventory if it fails multiple times, and


inventoryFallback returns a safe response instead.

Conclusion
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.

Spring Boot Microservices Java Programming Spring

Some rights reserved

Follow

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 9/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Written by Bishwa Poudel


15 Followers

Software Engineer

Recommended from Medium

Shazin Sadakath

5 Websites all Java Software Engineers must know and use


Java is 28 years old this year. That is a very long time and arguably Java could be considered as
“#1 programming language for today’s…

Sep 4 72

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 10/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Vinotech

End-to-End CI/CD Pipeline for Production-Ready Spring Boot


Applications
To create a comprehensive CI/CD pipeline for your Spring Boot application, you should include
several stages that cover the entire software…

Oct 16 31 1

Lists

General Coding Knowledge


20 stories · 1695 saves

Coding & Development


11 stories · 882 saves

Stories to Help You Grow as a Software Developer


19 stories · 1453 saves

ChatGPT
21 stories · 856 saves

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 11/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Nithidol Vacharotayan

Spring Boot 3 Deploy on Docker


Spring Boot 3 can be deployed on Docker with a jar file integrated with Dockerfile and docker-
compose. The developer can pack a jar file…

Jun 14 46

Serxan Hamzayev in Javarevisited

Spring Data JPA: Optimizing Performance with Pagination, Sorting, and


Filtering Using Specification

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 12/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

As applications grow, the need to fetch and manipulate large datasets becomes critical.
Pagination and sorting are essential tools to…

Oct 25 69

Rabinarayan Patra

Implementing an OTP Service in Java Using 2Factor API: A Step-by-Step


Guide

Oct 25 56 2

Auriga Aristo in Indonesian Developer

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 13/14
11/3/24, 11:14 PM Advanced Error Handling in Spring Boot Microservices | by Bishwa Poudel | Oct, 2024 | Medium

Mastering Entity Persistence


A Comprehensive Guide to Managing Entity States for Reliable Database Interaction.

Oct 26 20

See more recommendations

https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 14/14

You might also like