I have an ASP.NET Web API web service which throws a SerializationException in certain circumstances. The problem is that I'm unable to trap and log this exception server-side -- the only place it shows up is in the body of the HTTP response to the client.
I registered an ExceptionFilterAttribute
as described in Exception Handling in ASP.NET Web API and verified that it works properly when I throw an exception within my controller. Unfortunately the SerializationException is being thrown during the response (after the controller) and appears to be completely swallowed up by ASP.NET. I also tried hooking Application_Error()
in Global.asax.cs but it didn't show up there either.
How can I catch SerializationException exceptions during the Web API response?
BTW, Serialization of responses actually happens at the host layers(in HttpControllerHandler, when hosted in IIS and in HttpSelfhostServer, when hosted in SelfHost) which is way below the stack and not immediately after the response is returned from an action.
WebAPI Stack Poster: http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster-grayscale.pdf
That said, I am not able to come up with a straight forward way to achieve this. This is cumbersome, but may be override the default Xml and Json formatter's WriteToStreamAsync methods and try-catch-log any exceptions?
Alternatively, you can enable Web API Tracing which would log the exceptions happening during serialization. But yeah, if you do not know for the requests which cause the serialization errors, then you might want to enable tracing all the time which i am not sure is something you might want to do.
If, instead of returning an object, you use the ApiController.CreateResponse()
method and return a HttpResponseMessage
you can then do response.Content.LoadIntoBufferAsync().Wait()
and that will force the serialization to happen whilst you are still in the action and therefore can catch the exception.
You can catch all Web API exceptions by registering an implementation of IExceptionHandler
.
See Web API Global Error Handling
...there are a number of cases that exception filters can’t handle. For example:
- Exceptions thrown from controller constructors.
- Exceptions thrown from message handlers.
- Exceptions thrown during routing.
- Exceptions thrown during response content serialization .
One thing not mentioned in that article is that your IExceptionHandler
must be registered, either by GlobalConfiguration.Configuration.Services.Add(...)
or via an IoC container configured to be used by DependencyResolver
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With