Issue
How to propagate exceptions from one microservice to another in the spring Boot application.
Ex: when we make a get rest call then we would expect some valid response. Let's say we are expecting a response of type Long. But if there is An exception thrown from the other microservice then how it should be caught and handled in calling the microservice?
Currently, we are getting a deserialization issue in the token objects.
Solution
I would use @ControllerAdvice
to catch different types of exception which would occur in one microservice, and would send 5XX response code to inform other service that it was not able to process the request correctly, asit is considered a good practise to talk in response codes. PFB an example code.
@ControllerAdvice
public class MicroserviceExceptionHandler {
@ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
public final ResponseEntity handleException(Exception ex, WebRequest request) {
String errorMessage = ex.getMessage();
return ResponseEntity(HttpStatus.NOT_FOUND)
.status(HttpStatus.FORBIDDEN)
.body(errorMessage);
But if it required for your microservices to send the whole stack trace instead of just the message, then use below code to convert the stacktrace as a string and send it instead of ex.getMessage()
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Answered By - pranjal thakur
Answer Checked By - Cary Denson (JavaFixing Admin)