在我的 Azure API 管理策略中,我正在检查一些标头,并根据发现的内容执行某些操作。
当没有任何条件匹配时(即在
otherwise
块中),如何抛出错误
<policies>
<inbound>
<choose>
<when condition="">
</when>
<when condition="">
</when>
<otherwise>
</otherwise>
</choose>
<base/>
</inbound>
<backend>
<base/>
</backend>
<outbound>
<base/>
</outbound>
<on-error>
<base/>
</on-error>
</policies>
我可能想返回 401,因为我正在检查标题中的组。
已接受的解决方案的缺点是必须从头开始构建响应。如果您想标准化错误响应,这会变得很困难。我发现以下 hack 效果很好:
<set-variable name="Error" value="@{ throw new Exception("400:ERR_001"); }" />
这会让您陷入错误,并带有
ExpressionValueEvaluationFailure
。然后您可以解析出错误代码/状态:
<choose>
<when condition="@(context.LastError.Reason == "ExpressionValueEvaluationFailure" && string.IsNullOrEmpty(context.Variables.GetValueOrDefault<string>("ErrorCode")))">
<set-variable name="ErrorCode" value="@{
var match = Regex.Match(context.LastError.Message, @"^Expression evaluation failed\. (?:(\d{3}):)?(\w+_\d{3})$");
return match.Success ? match.Groups[2].Value : null;
}" />
<choose>
<when condition="@(!string.IsNullOrEmpty(context.Variables.GetValueOrDefault<string>("ErrorCode")))">
<set-status code="@{
var match = Regex.Match(context.LastError.Message, @"^Expression evaluation failed\. (?:(\d{3}):)?(\w+_\d{3})$");
return match.Success ? int.Parse(match.Groups[1].Value) : 500;
}" />
</when>
</choose>
</when>
</choose>
然后您可以在错误响应中使用 ErrorCode 变量。