【问题标题】:How to globally handle exceptions in asp.net web api when exception is raised through lambda expression通过lambda表达式引发异常时如何在asp.net web api中全局处理异常
【发布时间】:2015-03-03 09:39:12
【问题描述】:

我的 web api 项目中有一个全局异常处理程序。这工作正常,除非通过 lambda 表达式引发异常。 我在下面提供了一个示例代码:

[HttpGet]
public IHttpActionResult Test()
{
    //Throw new Exception();// this exception is handled by my ExceptionHandler
    var list = new List<int>();
    list.Add(1);
    IEnumerable<int> result = list.Select(a => GetData(a));
    return Ok(result);
}

private static int GetData(int a)
{
    throw new Exception();//This is not handled by my global exception handler
}

这是我的全局异常处理程序

public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        //Do something
    }
}

我在我的 WebApiConfig 类中注册它

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "Get", id = RouteParameter.Optional }
        );
        config.Filters.Add(new ExceptionHandlerAttribute());
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-web-api lambda


    【解决方案1】:

    ExceptionFilterAttribute 仅适用于在您的操作方法中 抛出的异常,请参阅Exception Handling in ASP.NET Web API - Exception Filters。您的代码将在结果实现期间引发异常,从而导致SerializationException

    Global Error Handling in ASP.NET Web API 2中所述:

    一些未处理的异常可以通过异常过滤器进行处理,但有很多情况是异常过滤器无法处理的。例如:

    • 控制器构造函数抛出异常。
    • 消息处理程序引发的异常。
    • 路由期间抛出异常。
    • 响应内容序列化过程中引发的异常

    注册一个异常处理程序或记录器并采取适当的行动:

    我们提供了两个新的用户可替换服务,IExceptionLogger 和 IExceptionHandler,用于记录和处理未处理的异常。这些服务非常相似,主要有两个区别: 我们支持注册多个异常记录器,但只支持一个异常处理程序。

    1. 总是会调用异常记录器,即使我们即将中止连接。
    2. 只有在我们仍然能够选择要发送的响应消息时才会调用异常处理程序。

    请参阅this answer in How do I log ALL exceptions globally for a C# MVC4 WebAPI app? 了解两者的实现。

    你当然也可以在你的控制器中实现可枚举,导致异常被抛出并由异常过滤器处理:

    var result = list.Select(a => GetData(a)).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2014-11-10
      相关资源
      最近更新 更多