2017-02-26 178 views
0

我有一個錯誤處理的路線:Apache Camel:我如何從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 

回答

0

我的錯誤在這裏是我使用的異常的類型。

爲了得到由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()); 

} 
0

嘗試啓用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"/> 

+0

這是行不通的。我想獲得請求正文。對我來說,使用原始消息,不要改變任何東西。 –

0

駱駝發出HTTP調用時,對待其他任何HTTP響應代碼比200的失敗,所以你需要到setThrowExceptionOnFailure爲false以指示camel路由忽略http響應代碼並返回接收的任何主體。

這裏是Java DSL例如:

getContext().getEndpoint(endpoint, HttpEndpoint.class).setThrowExceptionOnFailure(false); 

確保端點是主機:端口不作任何HTTP路徑,它做了精確匹配。

參見:http://camel.apache.org/http.html,尋找throwExceptionOnFailure

請注意,如果你把它設置爲false,那麼駱駝不會去異常處理的路線,它返回正常的,你需要處理的錯誤響應駱駝路線之外。我認爲這種方式更好,因爲您可以完全響應您所調用的服務,並且可以根據響應中的實際失敗代碼/原因執行錯誤處理。

+0

謝謝,好點。但在這一刻,我只需要獲取響應主體並將其追加到原始主體以獲取任何響應代碼!= 200.我認爲使用setThrowExceptionOnFailure對我來說不是一個好方法。 –

+0

問題是,如果您沒有將throwExceptionOnFailure設置爲false,那麼Camel只會查看HTTP響應代碼並將駱駝異常中的實際響應主體包裹在某處。我發現最簡單的方法是告訴Camel返回Camel收到的任何東西,你可以將請求主體放在某個地方,這樣你可以附加響應請求,或者使用.enrich()而不是.to(),然後你可以實現你的自己的聚合器。 –