【问题标题】:How to handle exception RabbitMQ Microservice如何处理异常 RabbitMQ 微服务
【发布时间】:2021-09-26 08:17:06
【问题描述】:

我使用的是 spring boot rabbitMQ Sender。 方法返回Integer

try {
    return rabbitTemplate.convertSendAndReceive(exchange, routingKey,
        mapper.writeValueAsString(request),
        correlationData);
} catch (Exception e) {
    log.error(e.getMessage(), e);
}

在接收方,回复:

@RabbitListener(queues = "testQueue", returnExceptions = "true")
public class TestReply {

    @RabbitHandler
    public Integer handle(String message) throws JsonProcessingException {
        throw new IllegalArgumentException()
    }
}

我想在发件人中处理IllegalArgumentException。但我得到的事实是

org.springframework.amqp.support.converter.MessageConversionException: Failed to convert Message content
Cannot deserialize value of type `java.lang.Integer` from Object value (token `JsonToken.START_OBJECT`)

请帮帮我!

【问题讨论】:

  • 我认为在“IllegalArgException”之前引发了另一个异常
  • 我认为收到 1 个异常,但它正在尝试转换为整数值。

标签: java spring-boot rabbitmq spring-rabbit


【解决方案1】:

@RabbitListener.returnExceptions().

    /**
     * Set to "true" to cause exceptions thrown by the listener to be sent to the sender
     * using normal {@code replyTo/@SendTo} semantics. When false, the exception is thrown
     * to the listener container and normal retry/DLQ processing is performed.
     * @return true to return exceptions. If the client side uses a
     * {@code RemoteInvocationAwareMessageConverterAdapter} the exception will be re-thrown.
     * Otherwise, the sender will receive a {@code RemoteInvocationResult} wrapping the
     * exception.
     * @since 2.0
     */
    String returnExceptions() default "";

但是,这仅适用于 Java 序列化(不是 JSON),因为异常通常不是 JSON 友好的。

另一种方法是添加errorHandler 并返回一些特殊值来告诉客户端发生了异常。

https://docs.spring.io/spring-amqp/docs/current/reference/html/#annotation-error-handling

【讨论】:

  • 谢谢你的回复,我试试看。非常感谢
最近更新 更多