如何在 Azure API 管理策略中引发错误?

问题描述 投票:0回答:2

在我的 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,因为我正在检查标题中的组。

azure-api-management
2个回答
6
投票

您可以使用

<choose>
策略来检测并报告失败,返回 401 响应。

<otherwise>
    <return-response >
        <set-status code="401" reason="Unauthorized" />
        <set-header name="WWW-Authenticate" exists-action="override">
            <value>Bearer error="invalid_token"</value>
        </set-header>
    </return-response>
</otherwise>

这里还有一个类似的SO线程你可以参考一下。


0
投票

已接受的解决方案的缺点是必须从头开始构建响应。如果您想标准化错误响应,这会变得很困难。我发现以下 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 变量。

© www.soinside.com 2019 - 2024. All rights reserved.