Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LSTANCZYK/70a176b3f8cc6bb9a0c1a0876452bb50 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/70a176b3f8cc6bb9a0c1a0876452bb50 to your computer and use it in GitHub Desktop.
How to tell Web API 2.1 to allow errors to propagate up the MessageHandler pipeline so all exceptions can be converted to HttpResponseMessages in one place.
class Program
{
static void Main(string[] args)
{
var server = WebApp.Start("http://localhost:1002/", (app) =>
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Services.Replace(typeof(IExceptionHandler), new RethrowExceptionHandler());
config.MessageHandlers.Add(new ErrorTrapHandler());
app.UseWebApi(config);
});
Console.ReadLine();
server.Dispose();
}
}
public class RethrowExceptionHandler : IExceptionHandler {
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
return Task.FromResult(0);
}
}
public class ErrorTrapHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
return await base.SendAsync(request, cancellationToken);
}
catch (Exception ex)
{
return new HttpResponseMessage
{
ReasonPhrase = ex.Message,
StatusCode = HttpStatusCode.InternalServerError
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment