Advanced Error Handling in Spring Boot Microservices _ by Bishwa Poudel _ Oct, 2024 _ Medium - Copy
Advanced Error Handling in Spring Boot Microservices _ by Bishwa Poudel _ Oct, 2024 _ Medium - Copy
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
@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);
}
}
@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
Clients receive an error response containing errorId , which they can report back to
support, linking them directly to the detailed logs.
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
Feign Configuration
Define a Feign client with fallback support:
@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");
}
}
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
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
<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.
super(message);
}
}
@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;
}
}
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:
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
@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);
}
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
</dependency>
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
Conclusion
Advanced error handling in Spring Boot microservices includes:
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.
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
Software Engineer
Shazin Sadakath
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
Oct 16 31 1
Lists
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
Jun 14 46
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
Oct 25 56 2
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
Oct 26 20
https://medium.com/@bishwapoudel/advanced-error-handling-in-spring-boot-microservices-fec7fbb0d0df 14/14