Created
January 21, 2014 20:54
-
-
Save darrelmiller/8548166 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.
This file contains hidden or 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
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
here is an example where your error handling would fail:
In your example the error stays unhandled and a Framework-generated 500 comes down.
If you use a proper exception handler it's handled correctly, and a custom HttpResponseMessage can be set: