Last active
August 29, 2015 14:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WebApiApplication : System.Web.HttpApplication | |
{ | |
protected void Application_Start() | |
{ | |
//... | |
GlobalConfiguration.Configuration.MessageHandlers.Add(new TaskCanceledExceptionHandler()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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