Reputation: 93
I'm currently trying to refactor some error handling routines in our Apigee endpoints. Clients can request JSON or XML data to be returned and this extends to the format of the error messages also. To reduce duplicate code I am attempting to keep all errors in JSON and only convert to XML when needed rather than having both versions of the error in the flows.
As an example when an invalid API key is used my error handler runs and creates a JSON version of our error response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="401-unauthorized-json">
<DisplayName>401UnAuthorized - JSON</DisplayName>
<FaultRules/>
<Properties/>
<Set>
<Payload contentType="application/json">
{"error":{
"Fault":{
"Error Code": "401",
"Description":"UnAuthorized",
"Response": "Invalid Apikey. Access Denied"
}
}}
</Payload>
<StatusCode>401</StatusCode>
<ReasonPhrase>Unauthorized</ReasonPhrase>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>
The JSON to XML policy itself is essentially empty with no special options:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<JSONToXML async="false" continueOnError="false" enabled="true" name="JSON-to-XML">
<DisplayName>JSON to XML 1</DisplayName>
<FaultRules/>
<Properties/>
<Options/>
<OutputVariable>response</OutputVariable>
<Source>response</Source>
</JSONToXML>
This policy is referenced in the 'DefaultFaultRule' for my proxy endpoint:
<DefaultFaultRule>
<Step>
<FaultRules/>
<Name>401-unauthorized-json</Name>
</Step>
<Step>
<Condition>(request.header.Accept ~ "*xml")</Condition>
<FaultRules/>
<Name>JSON-to-XML</Name>
</Step>
<AlwaysEnforce>true</AlwaysEnforce>
</DefaultFaultRule>
When the accept header is set to xml the JSON-to-XML is run but it fails with an error 500. The error being thrown is "JSONToXML[JSON-to-XML]: Source response is not available"
The assign message policy puts the error string into the response object and it works fine when JSON is returned. Why is JSON-to-XML complaining that the response object is not valid? What object should I be putting my error into with the assign message policy so this conversion works properly?
Upvotes: 1
Views: 1140
Reputation: 1990
The AssignMessage and JSONToXML policies will use reasonable contextual defaults when the source and destination variables are not provided. During a response flow, for example, leaving these fields off will cause the response message to be modified. This also works in FaultRules.
Remove the AssignTo element in the AssignMessage policy and the Source and OutputVariable elements in the JSONToXML policy, and your DefaultFaultRule flow should work.
Upvotes: 2