webapi:在全局异常处理程序中设置消息

webapi: set message in global exception handler

在我的 webapi 项目中,我有一个全局异常处理程序,我想在未捕获异常时设置状态代码 500,并且我想设置自定义消息,但我不知道如何设置该消息。这是我的代码:

public class MyExceptionHandler : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        context.Result = new StatusCodeResult(HttpStatusCode.InternalServerError, context.Request);

        return Task.FromResult<object>(null);
    }
}

配置为:

        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

        config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());

在邮递员中,响应主体是空的,我只看到 500 错误代码。那么这里怎么设置留言呢?

这是一个例子:

public class ExceptionFilter : ExceptionFilterAttribute
{
    private TelemetryClient TelemetryClient { get; }

    public ExceptionFilter(TelemetryClient telemetryClient)
    {
        TelemetryClient = telemetryClient;
    }

    public override void OnException(ExceptionContext context)
    {
        context.ExceptionHandled = true;
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
        context.Result = new JsonResult(new
        {
            error = context.Exception.Message
        });

        TelemetryClient.TrackException(context.Exception);
    }
}

您可以在启动时使用它 - ConfigureService:

services.AddSingleton<ExceptionFilter>();
services.AddMvc(
                options => { options.Filters.Add(services.BuildServiceProvider().GetService<ExceptionFilter>()); });

它现在还会向 azure 遥测发送异常。

您当然可以删除遥测客户端和方法:)

干杯!