/// <summary>
/// Called by Send method if an exception occurs, for instance a System.Net.WebException because the server
/// returned an HTTP error code. Override if you want to handle specific exceptions or always want to parse the
/// response to a custom ErrorResponse DTO type instead of ServiceStack's ErrorResponse class. In case ex is a
/// <c>System.Net.WebException</c>, do not use
/// <c>createWebRequest</c>/<c>getResponse</c>/<c>HandleResponse<TResponse></c> to parse the response
/// because that will result in the same exception again. Use
/// <c>ThrowWebServiceException<YourErrorResponseType></c> to parse the response and to throw a
/// <c>WebServiceException</c> containing the parsed DTO. Then override Send to handle that exception.
/// </summary>
protected virtual bool HandleResponseException <TResponse>(Exception ex, object request, string requestUri,
Func <WebRequest> createWebRequest, Func <WebRequest, WebResponse> getResponse, out TResponse response)
{
try
{
if (WebRequestUtils.ShouldAuthenticate(ex, this.UserName, this.Password))
{
// adamfowleruk : Check response object to see what type of auth header to add
var client = createWebRequest();
var webEx = ex as WebException;
if (webEx != null && webEx.Response != null)
{
WebHeaderCollection headers = ((HttpWebResponse)webEx.Response).Headers;
var doAuthHeader = headers[HttpHeaders.WwwAuthenticate];
// check value of WWW-Authenticate header
if (doAuthHeader == null)
{
client.AddBasicAuth(this.UserName, this.Password);
}
else
{
this.authInfo = new AuthenticationInfo(doAuthHeader);
client.AddAuthInfo(this.UserName, this.Password, authInfo);
}
}
if (OnAuthenticationRequired != null)
{
OnAuthenticationRequired(client);
}
var webResponse = getResponse(client);
response = HandleResponse <TResponse>(webResponse);
return(true);
}
}
catch (Exception subEx)
{
// Since we are effectively re-executing the call,
// the new exception should be shown to the caller rather
// than the old one.
// The new exception is either this one or the one thrown
// by the following method.
ThrowResponseTypeException <TResponse>(request, subEx, requestUri);
throw;
}
// If this doesn't throw, the calling method
// should rethrow the original exception upon
// return value of false.
ThrowResponseTypeException <TResponse>(request, ex, requestUri);
response = default(TResponse);
return(false);
}