如何处理异常 RabbitMQ 微服务

How to handle exception RabbitMQ Microservice

我使用 spring 引导 rabbitMQ 发送器。 方法returnsInteger

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`)

请帮帮我!

@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 和 return 一些特殊值来告诉客户端发生了异常。

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