private void HandleResponseError <TResponse>(Exception exception, AsyncState <TResponse> state)
{
var webEx = exception as WebException;
if (webEx.IsWebException())
{
var errorResponse = ((HttpWebResponse)webEx.Response);
Log.Error(webEx);
Log.DebugFormat("Status Code : {0}", errorResponse.StatusCode);
Log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription);
var serviceEx = new WebServiceException(errorResponse.StatusDescription)
{
StatusCode = (int)errorResponse.StatusCode,
};
try
{
using (var stream = errorResponse.GetResponseStream())
{
//Uncomment to Debug exceptions:
//var strResponse = new StreamReader(stream).ReadToEnd();
//Console.WriteLine("Response: " + strResponse);
//stream.Position = 0;
serviceEx.ResponseBody = stream.ReadFully().FromUtf8Bytes();
stream.ResetStream();
serviceEx.ResponseDto = this.StreamDeserializer(typeof(TResponse), stream);
state.HandleError((TResponse)serviceEx.ResponseDto, serviceEx);
}
}
catch (Exception innerEx)
{
// Oh, well, we tried
Log.Debug(string.Format("WebException Reading Response Error: {0}", innerEx.Message), innerEx);
state.HandleError(default(TResponse), new WebServiceException(errorResponse.StatusDescription, innerEx)
{
StatusCode = (int)errorResponse.StatusCode,
});
}
return;
}
var authEx = exception as AuthenticationException;
if (authEx != null)
{
var customEx = WebRequestUtils.CreateCustomException(state.Url, authEx);
Log.Debug(string.Format("AuthenticationException: {0}", customEx.Message), customEx);
state.HandleError(default(TResponse), authEx);
}
Log.Debug(string.Format("Exception Reading Response Error: {0}", exception.Message), exception);
state.HandleError(default(TResponse), exception);
CancelAsyncFn = null;
}