java - 如何处理异常 RabbitMQ 微服务
问题描述
我使用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`)
请帮我!
解决方案
@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
推荐阅读
- python - 简单插补 - 返回值 Err
- python - 如何使用其值对字典进行排名
- spring - 无法将“java.lang.String”类型的值转换为所需的“java.util.Date”类型
- python - Django ORM SQL 原始 Mysql
- javascript - 全局暴露了一个 es6 模块但为空
- php - 使用 php 解析 SOAP API
- react-native - React-Native textInput 添加数字而不是添加数字
- reactjs - 使用 axios 向 elasticsearch 发送请求以映射卡片
- python - Discord Bot 上的循环功能不起作用
- powerbi - 计算连续行之间的百分比差异 - Power BI