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

时间:2017-10-04 10:24:24

标签: c# asp.net-web-api exception-handling

在我的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错误代码。那么如何在这里设置消息呢?

1 个答案:

答案 0 :(得分:0)

以下是一个例子:

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>()); });

它现在也会向天蓝色遥测发送异常。

你可以在offcourse中删除遥测客户端和方法:)

喝彩!