How to globally handle exceptions in asp.net web api when an exception is raised via lambda expression

I have a global exception handler in my web api project. This works great unless an exception is expressed through a lambda expression. I gave an example code below:

[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 } 

This is my global exception handler.

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

I will register it in my WebApiConfig class

 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()); } } 
+6
source share
1 answer

ExceptionFilterAttribute only works for exceptions created in your action method, see Handling Exceptions in ASP.NET Web API - Exception Filters . Your code throws an exception during the materialization of the result, raising a SerializationException .

As explained in Global Error Handling in ASP.NET Web API 2 :

Some unhandled exceptions can be handled with exception filters, but there are a number of cases where exception handlers cannot be handled. For instance:

  • Exceptions thrown from controller constructors.
  • Exceptions thrown from message handlers.
  • Exceptions thrown during routing.
  • Exceptions that occur when serializing response content .

Register a handler or error logger and act accordingly:

We provide two new plug-in services, IExceptionLogger and IExceptionHandler, for registering and handling unhandled exceptions. The services are very similar, with two main differences: We support the registration of several exception logs, but only one exception handler.

  • Exception logs are always called, even if they were about to disconnect.
  • Exception handlers are called only when they can still select the response message to send.

See this answer in the section How to log ALL exceptions worldwide for a C # MVC4 WebAPI application? to implement both.

Of course, you can also materialize the enumerated in your controller, forcing the exception to get out and process the exception filter:

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

Source: https://habr.com/ru/post/983257/


All Articles