If the specified JSON is returned from backend service, you can retrieve the code and status in the following way. This is a simple example, and few error handling is implemented. You should care about this.
The following points should be considered.
- Liquid template does not work in
set-body
ofreturn-response
policy.https://learn.microsoft.com/en-us/azure/api-management/return-response-policy
- The original message body stream is unavailable after calling
context.Response.Body.As<JObject>()
. To avoid this, you should set thepreserveContent
parameter totrue
.
[Response from backend service]
{
"error": {
"status": 0,
"code": "string",
"message": "string",
"target": "string",
"instance": "string",
"details": [
"string"
]
}
}
[policy]
...
<outbound>
<base />
<return-response>
<set-status code="200" />
<set-body>@{
var body = context.Response.Body.As<JObject>(true);
if(body["error"]!= null && body["error"].HasValues ) {
return new JObject(
new JProperty("code", (string)body["error"]["code"]),
new JProperty("status", (int)body["error"]["status"])
).ToString();
}
}</set-body>
</return-response>
</outbound>
...