Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active August 29, 2015 14:01
Show Gist options
  • Save reidev275/fe1e290fb527255607ab to your computer and use it in GitHub Desktop.
Save reidev275/fe1e290fb527255607ab to your computer and use it in GitHub Desktop.
Catches otherwise uncaught TaskCanceledException objects. Useful with WebApi and async await programming. We get a handle to the buffer so that we can replay the reading of the buffer for logging purposes later.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//...
GlobalConfiguration.Configuration.MessageHandlers.Add(new TaskCanceledExceptionHandler());
}
}
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MvcApplication1.App_Start
{
public class TaskCanceledExceptionHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
using (var buffer = await request.Content.ReadAsStreamAsync())
{
try
{
return await base.SendAsync(request, cancellationToken);
}
catch (TaskCanceledException e)
{
string content = "";
if (buffer.CanSeek && buffer.CanRead)
{
buffer.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(buffer))
{
content = reader.ReadToEnd();
}
}
return request.CreateErrorResponse(HttpStatusCode.InternalServerError, request.ToString() + ", " + "Content: " + content, e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment