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

如何在Azure Function启动类中配置中间件异常处理器?

Azure Function App 添加异常处理中间件的实现方案

Azure Function App支持添加中间件(包括异常处理中间件),但实现逻辑和ASP.NET Web应用的IApplicationBuilder配置方式不同,需要根据Functions的宿主模型(In-Process/Isolated Worker)适配实现。

一、In-Process 模型(你的当前场景,已使用Startup类)

1. 实现自定义异常处理中间件

创建实现IMiddleware接口的中间件类,在InvokeAsync方法中捕获并处理异常:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Threading.Tasks;

public class ExceptionHandlingMiddleware : IMiddleware
{
    public async Task InvokeAsync(FunctionContext context, Func<Task> next)
    {
        try
        {
            // 执行后续中间件与函数逻辑
            await next();
        }
        catch (Exception ex)
        {
            // 记录异常日志
            var logger = context.GetLogger<ExceptionHandlingMiddleware>();
            logger.LogError(ex, "函数 {FunctionName} 发生未处理异常", context.FunctionDefinition.Name);

            // 针对HTTP触发的函数,自定义错误响应
            if (context.BindingContext.TryGetValue("HttpResponse", out var responseObj) 
                && responseObj is HttpResponseData response)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                await response.WriteStringAsync("服务发生意外错误,请稍后重试。");
            }
        }
    }
}

2. 在Startup类中注册中间件

在Configure方法中通过AddMiddleware扩展方法注册你的异常处理中间件:

public override void Configure(IFunctionsHostBuilder builder)
{
    // 保留你已有的服务注册逻辑
    // builder.Services.....

    // 注册异常处理中间件
    builder.Services.AddMiddleware<ExceptionHandlingMiddleware>();
}

二、Isolated Worker 模型(若后续切换宿主模型参考)

如果使用Isolated Worker模型(.NET 6+),需在Program.cs中配置中间件:

1. 实现中间件类

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Threading.Tasks;

public class ExceptionHandlingMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            var logger = context.GetLogger<ExceptionHandlingMiddleware>();
            logger.LogError(ex, "函数 {FunctionName} 发生未处理异常", context.FunctionDefinition.Name);

            // 处理HTTP触发的响应
            if (context.GetHttpResponseData() is HttpResponseData response)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                await response.WriteStringAsync("服务发生意外错误,请稍后重试。");
            }
        }
    }
}

2. 注册中间件

using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(app =>
    {
        // 添加异常处理中间件
        app.UseMiddleware<ExceptionHandlingMiddleware>();
    })
    .Build();

host.Run();

注意事项

  • 中间件支持从.NET 6版本的Azure Functions开始提供,确保你的项目目标框架为.NET 6或更高。
  • 非HTTP触发的函数(如队列、定时器),中间件可完成日志记录等操作,但无法修改响应(无HTTP响应对象)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:45:04