我一直在一个项目上使用Apache Camel,我需要在我调用的API响应抛出异常时返回它。
<route customId="true" id="restrictionsBlackList" streamCache="false">
<from uri="direct:restrictionsBlackList" />
<setHeader customId="true" id="StepNameDefinitionRBL" name="stepName">
<constant>restrictionsBlackList</constant>
</setHeader>
<setHeader customId="true" id="MethodNameRBL" name="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<doTry>
<setProperty customId="true" id="ProspectDefinitionRBL" name="prospect">
<jsonpath>$.request.body.prospect</jsonpath>
</setProperty>
<log customId="true" id="LogProspectDefinitionRBL" message="prospect ${exchangeProperty[prospect]}" />
<setProperty customId="true" id="SearchDefinition" name="search">
<jsonpath>$.request.body.search</jsonpath>
</setProperty>
<log customId="true" id="LogSearchDefinitionRBL" message="search ${exchangeProperty[search]}" />
<setProperty customId="true" id="CompositionDefinition" name="compositions">
<jsonpath>$.request.body.compositions</jsonpath>
</setProperty>
<!-- headers -->
<setHeader name="X-Company-Id">
<simple>${exchangeProperty[companyId]}</simple>
</setHeader>
<setHeader name="X-Application-Id">
<simple>${exchangeProperty[applicationId]}</simple>
</setHeader>
<to customId="true" id="URLRestrictionBlackList" uri="{{RESTRICTIONS_BLACKLIST_URL}}" />
<doCatch>
<exception>org.apache.camel.CamelException</exception>
<log message="body is : ${exception.responseBody}" />
</doCatch>
</doTry>
</route>
API正在返回以下消息。
{
"code": 16,
"message": "JWT validation failed: TIME_CONSTRAINT_FAILURE",
"details": [
{
"@type": "type.googleapis.com/google.rpc.DebugInfo",
"stackEntries": [],
"detail": "auth"
}
]
}
但当我重新抛出异常时,我得到的是这样的回报。
{
"message": "{\n \"code\": 16,\n \"message\": \"JWT validation failed: TIME_CONSTRAINT_FAILURE\",\n \"details\": [\n {\n \"@type\": \"type.googleapis.com/google.rpc.DebugInfo\",\n \"stackEntries\": [],\n \"detail\": \"auth\"\n }\n ]\n}\n",
"errors": []
}
我找到了一个替代方案,因为我使用的是Spring Boot,所以我最终选择为CamelException和CamelExecutionException添加一个特定的错误处理,并检查它们的来源是否是HttpOperationFailedException。
@ExceptionHandler({CamelException.class, CamelExecutionException.class})
public ResponseEntity<?> camelExchangeExceptions(CamelException ex) {
if (ex instanceof org.apache.camel.http.common.HttpOperationFailedException) {
org.apache.camel.http.common.HttpOperationFailedException exception = (org.apache.camel.http.common.HttpOperationFailedException) ex;
return ResponseEntity
.status(exception.getStatusCode())
.body(stringToJsonNode(exception.getResponseBody()));
}
if (ex.getCause() instanceof org.apache.camel.http.common.HttpOperationFailedException) {
org.apache.camel.http.common.HttpOperationFailedException exception = (org.apache.camel.http.common.HttpOperationFailedException) ex.getCause();
return ResponseEntity
.status(exception.getStatusCode())
.body(stringToJsonNode(exception.getResponseBody()));
}
return ResponseEntity
.status(499)
.body(new ApiErrorResponse(ex.getMessage()));
}