Handling the errors inside the SendAsync method of a Message Handler

Topics: ASP.NET Web API
Jul 16, 2012 at 1:55 PM

Is it expected to handle the errors inside the SendAsync method of Message Handler? for example the following code is from the BasicAuthenticationMessageHandler message handler I have:

try {

    //BasicAuth credentials has been extracted.
    //Authenticate the user now
    principal = AuthenticateUser(username, password);
catch (Exception e) {

    return TaskHelpers.FromError<HttpResponseMessage>(e);

Is this the expected practice? or there is no need to do this if the pipeline takes care of this for us?

Jul 16, 2012 at 9:44 PM

I think you need to return 401 instead of returning the exception. I think your code will send back 500 which is not good.

In other cases it is best to return the Task with appropriate state (faulted or successful)

Jul 16, 2012 at 10:10 PM

but that is not the case. I am sending back the faulted task because exception is thrown, we don't know if the user is authed or not.

If there is no exception, I am checking if the user is authed or not at the further stage: https://github.com/tugberkugurlu/WebAPIDoodle/blob/dev/src/apps/WebAPIDoodle/MessageHandlers/BasicAuthenticationMessageHandler.cs

Jul 16, 2012 at 10:59 PM
Edited Jul 16, 2012 at 11:00 PM

OK, so if that is considered an exception rather than unauthorised, then it is correct. Catching exception and returning faulted task allows for more organic pipeline (you could have MessageHandlers to do something in case of a faulted response) although it is not absolutely necessary and ASP.NET Web API can handle those kind of exceptions too.

Adding this handler to handlers does not cause a problem and error is handled gracefully:


public class ErrorThrowerHandler : DelegatingHandler
	protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
		throw new InvalidOperationException();
			return base.SendAsync(request, cancellationToken);