2017-10-04 67 views
0

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

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

+0

这将帮助您使用此解决方案配置客户错误消息http://www.dotnetcurry.com/aspnet/1133/aspnet-web-api-throw-custom-exception-message –

回答

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删除telemetryclient和方法:)

喝彩!

+0

,如果我有10个控制器,每个控制器都有它自己的异常类型,我需要添加10个过滤器...所以使用异常处理程序类不可能这样做? –

+0

@BudaGavril,你为什么需要这个? 'context.Exception'包含每个控制器可能抛出的异常。 –

+0

请参阅上面的注释...以便在添加新控制器和异常类型时,此异常由我的异常处理程序处理,而无需添加新过滤器或编辑一个现有的过滤器 –