Skip to content

Commit

Permalink
Merge pull request #12 from penguineer/send-correlated-error
Browse files Browse the repository at this point in the history
Send correlation ID with error messages if available
  • Loading branch information
penguineer authored Nov 6, 2024
2 parents 3b5fb43 + b4bd29f commit ff0bdce
Showing 1 changed file with 10 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public ChatRequestHandler(ObjectMapper objectMapper,
this.rateLimitGate = rateLimitGate;
}


/**
* Handles a chat request.
*
Expand Down Expand Up @@ -91,11 +90,7 @@ public void onMessage(Message message, Channel channel) {
String jsonResponse = serializeChatResponse(result);

// Send the response to the replyTo queue
MessageProperties messageProperties = new MessageProperties();
correlationId.ifPresent(messageProperties::setCorrelationId);
messageProperties.setContentType("application/json");
Message responseMessage = new Message(jsonResponse.getBytes(), messageProperties);
rabbitTemplate.send(replyTo, responseMessage);
send(jsonResponse, replyTo, correlationId);

// Acknowledge the message
channel.basicAck(deliveryTag, false);
Expand All @@ -109,14 +104,22 @@ public void onMessage(Message message, Channel channel) {
Optional<String> json = serializeChatError(e);
errorTo.ifPresentOrElse(
to -> json.ifPresent(
j -> rabbitTemplate.convertAndSend(to, j)),
j -> send(j, to, correlationId)),
() -> logger.error("Error on handling chat request!", e)
);

doExceptionBasedAck(e, channel, deliveryTag);
}
}

private void send(String json, String to, Optional<String> correlationId) {
MessageProperties messageProperties = new MessageProperties();
correlationId.ifPresent(messageProperties::setCorrelationId);
messageProperties.setContentType("application/json");
Message responseMessage = new Message(json.getBytes(), messageProperties);
rabbitTemplate.send(to, responseMessage);
}

private void doExceptionBasedAck(Exception e, Channel channel, long deliveryTag) {
try {
if (e instanceof ChatException chatException)
Expand Down

0 comments on commit ff0bdce

Please sign in to comment.