You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Event Grid触发的Azure Function的返回结果码?

Event Grid触发Azure Function自定义App Insights结果码实现方法

HTTP触发属于请求响应模型,直接修改context.res.status即可被App Insights自动采集;Event Grid触发为事件驱动模型,无原生HTTP响应结构,默认仅根据函数是否抛出未处理异常上报200/500两种状态码,需要通过自定义遥测的方式实现自定义状态码上报。

方法1:直接上报自定义请求遥测(最直接)

适用于所有语言的运行环境,以C#为例:

  • 首先安装对应NuGet包:Microsoft.ApplicationInsights.AspNetCore
  • 构造函数注入TelemetryClient实例
  • 业务逻辑中根据需要设置自定义状态码,主动上报请求遥测:
public class EventGridFunction
{
    private readonly TelemetryClient _telemetryClient;

    public EventGridFunction(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    [FunctionName("EventGridTriggerDemo")]
    public void Run([EventGridTrigger] EventGridEvent eventData, FunctionContext context)
    {
        var invocationId = context.InvocationId;
        try
        {
            // 你的业务逻辑
            // 需要上报501的场景
            var requestTelemetry = new RequestTelemetry
            {
                Name = "EventGridTriggerDemo",
                ResponseCode = "501",
                Success = false,
                Timestamp = DateTimeOffset.Now
            };
            requestTelemetry.Properties["InvocationId"] = invocationId;
            _telemetryClient.TrackRequest(requestTelemetry);
        }
        catch (Exception ex)
        {
            // 异常场景也可以自定义状态码
            var requestTelemetry = new RequestTelemetry
            {
                Name = "EventGridTriggerDemo",
                ResponseCode = "自定义异常状态码",
                Success = false,
                Timestamp = DateTimeOffset.Now
            };
            _telemetryClient.TrackException(ex);
            _telemetryClient.TrackRequest(requestTelemetry);
        }
    }
}

如果是JavaScript/TypeScript函数,引入applicationinsights模块获取遥测客户端,调用trackRequest方法上报即可,逻辑和C#一致。

方法2:通过遥测初始化器修改自动采集的遥测数据

如果不想屏蔽默认的自动采集逻辑,可以通过自定义ITelemetryInitializer修改默认上报的状态码:

  • 自定义带状态码的业务异常类
  • 函数中需要返回自定义状态码时抛出对应异常
  • 实现ITelemetryInitializer,判断如果请求遥测关联了自定义业务异常,就修改ResponseCode属性为自定义值:
public class CustomStatusTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if (telemetry is RequestTelemetry requestTelemetry 
            && requestTelemetry.Properties.ContainsKey("ExceptionType") 
            && requestTelemetry.Properties["ExceptionType"] == nameof(CustomFunctionStatusException))
        {
            // 从异常属性中提取预先定义的自定义状态码即可
            requestTelemetry.ResponseCode = "501";
            requestTelemetry.Success = false;
        }
    }
}

然后在Program.cs中注册这个初始化器:

builder.Services.AddSingleton<ITelemetryInitializer, CustomStatusTelemetryInitializer>();

效果示意

界面示意图

内容的提问来源于stack exchange,提问作者iqoOopi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:15:02