[英]Apache Camel: How I get message returned from Rest API?
我有一條帶有錯誤處理程序的路由:
<route errorHandlerRef="magentoCustomerErrorHandler" id="customers.route2">
...
<to id="_to1" uri="http4://{{magento.api.url}}customer/"/>
</route>
在錯誤處理程序中,我在onRedelivery中調用處理器
<bean class="br.com.company.ProcessorError" id="myErrorProcessor"/>
<bean class="org.apache.camel.builder.DeadLetterChannelBuilder" id="magentoCustomerErrorHandler">
<property name="deadLetterUri" value="activemq:magento:customers:DQL"/>
<property name="onRedelivery" ref="myErrorProcessor"/>
<property name="redeliveryPolicy" ref="myRedeliveryPolicyConfig"/>
</bean>
在錯誤處理器中,我嘗試獲取API返回的消息,但僅獲取駱駝生成的消息。
ErrorProcessor類:
public void process(Exchange exchange) throws Exception {
Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
exchange.getIn().setHeader("FailedBecause", cause.getMessage());
}
API響應:
{"messages":{"error":[{"code":500,"message":"Token doesn't exist or is expired."}]}}
預期消息:
Token doesn't exist or is expired
返回消息:
HTTP operation failed invoking http://myurl.com/api/rest/customer/ with statusCode: 500
嘗試啟用useOriginalMessage
選項:
<bean class="org.apache.camel.builder.DeadLetterChannelBuilder" id="magentoCustomerErrorHandler">
<property name="deadLetterUri" value="activemq:magento:customers:DQL"/>
<property name="onRedelivery" ref="myErrorProcessor"/>
<property name="useOriginalMessage" value="true"/>
<property name="redeliveryPolicy" ref="myRedeliveryPolicyConfig"/>
Camel在進行http調用時會將200以外的任何HTTP響應代碼都視為失敗,因此您需要將setThrowExceptionOnFailure
為false,以指示駱駝路線忽略HTTP響應代碼,並只返回接收到的任何內容。
這是Java DSL示例:
getContext().getEndpoint(endpoint, HttpEndpoint.class).setThrowExceptionOnFailure(false);
確保端點僅是host:port,沒有任何http路徑,並且確實匹配。
參考: http : //camel.apache.org/http.html ,查找throwExceptionOnFailure
請注意,如果將其設置為false,那么駱駝將不會進入異常處理路線,它會像往常一樣返回,並且您需要在駱駝路線之外處理錯誤響應。 我認為這種方法更好,因為您可以從正在調用的服務獲得完整的響應,並且可以根據響應中的實際故障代碼/原因來進行錯誤處理。
我的錯誤是我使用的異常類型。
要獲取REST返回的正文,我需要使用HttpOperationFailedException。
ErrorProcessor類
public void process(Exchange exchange) throws Exception {
HttpOperationFailedException cause = (HttpOperationFailedException) exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
exchange.getIn().setHeader("FailedBecause", cause.getMessage());
exchange.getIn().setHeader("ResponseBody", cause.getResponseBody());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.