【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

问题描述

在为APIM服务配置了诊断日志(Diagnostic Setting),把日志收集在Log A Workspace中,需要验证日志中是否能查看到请求的错误信息。

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

所以想人为的来制造一些错误。经过网络搜索,参考Policy的文档介绍后,完成了以下3种错误

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

 

第一种:使用 return-response 返回指定错误码

return-response 策略会取消执行,为调用方返回默认响应或自定义响应。

默认响应为200 OK,无正文。

可以通过上下文变量或策略语句指定自定义响应。 二者都提供时,会通过策略语句对上下文变量中包含的响应进行修改,然后再将其返回给调用方。

如下的示例:自定义返回505错误,并且设置错误消息为 Bearer error="invalid_token"。

<policies>     <inbound>         <base />     </inbound>     <backend>         <base />     </backend>     <outbound>         <base />         <return-response>             <set-status code="505" reason="error0" />             <set-header name="WWW-Authenticate" exists-action="override">                 <value>Bearer error="invalid_token"</value>             </set-header>         </return-response>     </outbound>     <on-error>         <base />     </on-error> </policies>

效果展示:

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

 

 

第二种: 定义变量,直接抛出异常 @{ throw new Exception( ... ); }

set-variable 策略声明set-variable变量,并为其分配通过表达式或字符串文本指定的值。在赋值语句种直接抛出异常

并使用重试(retry)策略,让错误多次出现。使得诊断日志种生成的日志Errors中保存请求中产生的全部错误

<policies>     <inbound>         <base />     </inbound>     <backend>         <base />     </backend>     <outbound>         <set-variable name="Error" value="@{ throw new Exception("test one time error here:ERR_001"+DateTime.UtcNow.ToString("O")); }" />         <base />     </outbound>     <on-error>         <base />         <retry condition="@(505>= 500)" count="3" interval="1" first-fast-retry="true">             <set-variable name="Error" value="@{ throw new Exception("test n time error here :ERR_002 or n in retry policy"+DateTime.UtcNow.ToString("O")); }" />         </retry>     </on-error> </policies>

效果展示:

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

 

第三种:set-backend-service,设置错误域名,制造DNS解析错误

使用 set-backend-service 策略将传入请求重定向到一个后端,此后端不同于在 API 设置中为该操作指定的后端。比如:https://www.ted1111.com/

<policies>     <inbound>         <base />         <set-backend-service base-url="https://www.ted1111.com/" />     </inbound>     <backend>         <base />     </backend>     <outbound>         <base />     </outbound>     <on-error>         <base />     </on-error> </policies>

效果展示:

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

实际错误:

forward-request (32.859 ms) {     "messages": [         "Error occured while calling backend service.",         "The remote name could not be resolved: 'www.ted1111.com'"     ] }

 

汇总

在Log A Workspace中, 查看日志表 ApiManagementGatewayLogs 中所收集的这三种错误日志:

第一种错误:并没有Errors被记录,只有错误的状态码返回。

第二种错误:状态码为500。但是,在Errors包含了请求中生产的全部日志,非常有利于Debug。

第三种错误:状态码为500。同时,在Errors中,也包含了请求中的详细错误。

【Azure APIM】列举几种在APIM 策略中的主动生产的错误语句

 

参考资料

API 管理策略参考 : https://docs.azure.cn/zh-cn/api-management/api-management-policies

 
 

 

发表评论

相关文章