A base exception for some Amazon Web Services.

Most exceptions thrown to client code will be service-specific exceptions, though some services may throw this exception if there is a problem which is caught in the core client code.

Inheritance: System.Exception
Exemplo n.º 1
0
        bool handleHttpWebErrorResponse(AsyncResult asyncResult, WebException we)
        {
            HttpStatusCode         statusCode;
            AmazonServiceException errorResponseException = null;

            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
            {
                if (httpErrorResponse == null)
                {
                    // Abort the unsuccessful request
                    asyncResult.RequestState.WebRequest.Abort();

                    // If it is a keep alive error then attempt a retry
                    if (we != null && asyncResult.RetriesAttempt <= config.MaxErrorRetry && we.Status == WebExceptionStatus.KeepAliveFailure)
                    {
                        pauseExponentially(asyncResult.RetriesAttempt);
                        return(true);
                    }
                    throw new AmazonServiceException(we);
                }
                statusCode = httpErrorResponse.StatusCode;
                string redirectedLocation = httpErrorResponse.Headers["location"];

                using (httpErrorResponse)
                {
                    var unmarshaller = asyncResult.Unmarshaller;
                    UnmarshallerContext errorContext = unmarshaller.CreateContext(httpErrorResponse, config.LogResponse);
                    if (config.LogResponse)
                    {
                        this.logger.InfoFormat("Received error response: [{0}]", errorContext.ResponseBody);
                    }
                    errorResponseException = unmarshaller.UnmarshallException(errorContext, we, statusCode);
                }
                asyncResult.RequestState.WebRequest.Abort();

                if (isTemporaryRedirect(statusCode, redirectedLocation))
                {
                    this.logger.InfoFormat("Request {0} is being redirected to {1}.", asyncResult.RequestName, redirectedLocation);
                    asyncResult.Request.Endpoint = new Uri(redirectedLocation);
                    return(true);
                }
                else if (ShouldRetry(statusCode, this.config, errorResponseException, asyncResult.RetriesAttempt))
                {
                    this.logger.InfoFormat("Retry number {0} for request {1}.", asyncResult.RetriesAttempt, asyncResult.RequestName);
                    pauseExponentially(asyncResult.RetriesAttempt);
                    return(true);
                }
            }

            if (errorResponseException != null)
            {
                this.logger.Error(string.Format("Error making request {0}.", asyncResult.RequestName), errorResponseException);
                throw errorResponseException;
            }

            AmazonServiceException excep = new AmazonServiceException("Unable to make request", we, statusCode);

            this.logger.Error(string.Format("Error making request {0}.", asyncResult.RequestName), excep);
            throw excep;
        }
Exemplo n.º 2
0
        private static bool TryParseDateHeader(AmazonServiceException ase, out DateTime serverTime)
        {
            var webData = GetWebData(ase);

            if (webData != null)
            {
                // parse server time from "Date" header, if possible
                var dateValue = webData.GetHeaderValue(HeaderKeys.DateHeader);
                if (!string.IsNullOrEmpty(dateValue))
                {
                    if (DateTime.TryParseExact(
                            dateValue,
                            AWSSDKUtils.GMTDateFormat,
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal,
                            out serverTime))
                    {
                        return(true);
                    }
                }
            }

            serverTime = DateTime.MinValue;
            return(false);
        }
        private async Task <bool> HandleHttpErrorResponseAsync(WebRequestState state, HttpResponseMessage httpErrorResponse, HttpClientResponseData responseData, CancellationToken cancellationToken)
        {
            HttpStatusCode         statusCode;
            AmazonServiceException errorResponseException = null;

            UnmarshallerContext errorContext = null;

            statusCode = httpErrorResponse.StatusCode;
            state.Metrics.AddProperty(Metric.StatusCode, statusCode);
            string redirectedLocation = responseData.GetHeaderValue("location");

            state.Metrics.AddProperty(Metric.RedirectLocation, redirectedLocation);

            var responseStream = await responseData.ResponseBody.OpenResponseAsync()
                                 .ConfigureAwait(continueOnCapturedContext: false);

            errorContext = state.Unmarshaller.CreateContext(responseData,
                                                            Config.LogResponse || Config.ReadEntireResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never,
                                                            responseStream,
                                                            state.Metrics);
            errorResponseException = state.Unmarshaller.UnmarshallException(errorContext, null, statusCode);
            if (Config.LogResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never)
            {
                this.logger.Error(errorResponseException, "Received error response: [{0}]", errorContext.ResponseBody);
            }
            state.Metrics.AddProperty(Metric.AWSRequestID, errorResponseException.RequestId);
            state.Metrics.AddProperty(Metric.AWSErrorCode, errorResponseException.ErrorCode);

            if (CanRetry(state))
            {
                if (isTemporaryRedirect(statusCode, redirectedLocation))
                {
                    this.logger.DebugFormat("Request {0} is being redirected to {1}.", state.Request.RequestName, redirectedLocation);
                    state.Request.Endpoint = new Uri(redirectedLocation);
                    return(true);
                }
                else if (ShouldRetry(statusCode, this.Config, errorResponseException, state.RetriesAttempt))
                {
                    this.logger.DebugFormat("Retry number {0} for request {1}.", state.RetriesAttempt, state.Request.RequestName);
                    pauseExponentially(state);
                    cancellationToken.ThrowIfCancellationRequested();
                    return(true);
                }
            }

            if (errorResponseException != null)
            {
                this.logger.Error(errorResponseException, "Error making request {0}.", state.Request.RequestName);
                state.Metrics.AddProperty(Metric.Exception, errorResponseException);
                throw errorResponseException;
            }


            AmazonServiceException excep = new AmazonServiceException("Unable to make request", null, statusCode);

            this.logger.Error(excep, "Error making request {0}.", state.Request.RequestName);
            state.Metrics.AddProperty(Metric.Exception, excep);
            throw excep;
        }
Exemplo n.º 4
0
        private static bool TryParseDateHeader(AmazonServiceException ase, out DateTime serverTime)
        {
            IWebResponseData webData = GetWebData(ase);

            if (webData != null)
            {
                string headerValue = webData.GetHeaderValue("Date");
                if (!string.IsNullOrEmpty(headerValue) && DateTime.TryParseExact(headerValue, "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out serverTime))
                {
                    return(true);
                }
            }
            serverTime = DateTime.MinValue;
            return(false);
        }
        /// <summary>
        /// The HandleWWWErrorResponse differs significantly from the error handling doing in .NET sdk
        /// since the www.error string message is incomplete
        /// so this requires rewriting all responseunmarshallers.HandleErrorContext which is not part of this version
        /// hence exception thrown will always be of base type AmazonServiceException
        /// </summary>
        /// <returns>True if the error needs retry</returns>
        private bool HandleWWWErrorResponse(AsyncResult asyncResult)
        {
            WWWResponseData errorResponse = asyncResult.ResponseData;

            asyncResult.Metrics.AddProperty(Metric.Exception, errorResponse.Error);

            AmazonServiceException errorResponseException = null;

            errorResponseException = new AmazonServiceException(errorResponse.Error,
                                                                new WebException(errorResponse.Error));

            errorResponseException.UnityStatusCode = errorResponse.Error;
            try
            {
                errorResponseException.StatusCode = errorResponse.ErrorStatusCode;
            }
            catch (Exception e)
            {
                // Parsing exception
                AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, asyncResult.Request.RequestName, e);
            }

            string curl = "curl " + (asyncResult.Request.HttpMethod == "GET" &&
                                     !HttpOverrideSupportedServices.Contains(asyncResult.Request.ServiceName) ?
                                     "-G " :  "-X POST ");

            foreach (string key in asyncResult.RequestData.Headers.Keys)
            {
                curl += " -H \"" + key + ": " + asyncResult.RequestData.Headers[key] + "\" ";
            }
            if (asyncResult.RequestData.Data != null)
            {
                curl += " -d '" + System.Text.Encoding.Default.GetString(asyncResult.RequestData.Data) + "' ";
            }

            curl += " " + asyncResult.RequestData.Url;
            Debug.LogError(curl);

            if (errorResponse.IsHeaderPresent(HeaderKeys.XAmzRequestIdHeader.ToUpper()))
            {
                errorResponseException.RequestId = errorResponse.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader);
            }

            asyncResult.Exception = errorResponseException;

            // currently no retries are done
            return(false);
        }
Exemplo n.º 6
0
        private void processWebException <X, Y>(string requestName, WebException we, HttpWebRequest webRequest, IResponseUnmarshaller <Y, UnmarshallerContext> unmarshaller, IRequest <X> request, int retries)
        {
            HttpStatusCode         statusCode;
            AmazonServiceException errorResponseException = null;

            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
            {
                if (httpErrorResponse == null)
                {
                    // Abort the unsuccessful request
                    webRequest.Abort();
                    throw new AmazonServiceException(we);
                }
                statusCode = httpErrorResponse.StatusCode;

                XmlTextReader       errorReader  = new XmlTextReader(new StreamReader(httpErrorResponse.GetResponseStream()));
                UnmarshallerContext errorContext = new UnmarshallerContext(errorReader);
                errorResponseException = unmarshaller.UnmarshallException(errorContext, we, statusCode);

                httpErrorResponse.Close();
                webRequest.Abort();

                if (isTemporaryRedirect(httpErrorResponse))
                {
                    string redirectedLocation = httpErrorResponse.Headers["location"];
                    this.logger.InfoFormat("Request {0} is being redirected to {1}.", requestName, redirectedLocation);
                    request.Endpoint = new Uri(redirectedLocation);
                    return;
                }
                else if (ShouldRetry(statusCode, this.config, errorResponseException, retries))
                {
                    this.logger.InfoFormat("Retry number {0} for request {1}.", retries, requestName);
                    pauseExponentially(retries);
                    return;
                }
            }

            if (errorResponseException != null)
            {
                this.logger.Error(string.Format("Error making request {0}.", requestName), errorResponseException);
                throw errorResponseException;
            }

            AmazonServiceException excep = new AmazonServiceException("Unable to make request", we, statusCode);

            this.logger.Error(string.Format("Error making request {0}.", requestName), excep);
            throw excep;
        }
Exemplo n.º 7
0
 private static IWebResponseData GetWebData(AmazonServiceException ase)
 {
     if (ase != null)
     {
         Exception ex = ase;
         do
         {
             HttpErrorResponseException ex2 = ex as HttpErrorResponseException;
             if (ex2 != null)
             {
                 return(ex2.Response);
             }
             ex = ex.InnerException;
         }while (ex != null);
     }
     return(null);
 }
Exemplo n.º 8
0
        private static IWebResponseData GetWebData(AmazonServiceException ase)
        {
            if (ase != null)
            {
                Exception e = ase;
                do
                {
                    var here = e as HttpErrorResponseException;
                    if (here != null)
                    {
                        return(here.Response);
                    }
                    e = e.InnerException;
                } while (e != null);
            }

            return(null);
        }
Exemplo n.º 9
0
        private static bool TryParseExceptionMessage(AmazonServiceException ase, out DateTime serverTime)
        {
            if (ase != null && !string.IsNullOrEmpty(ase.Message))
            {
                var message = ase.Message;

                // parse server time from exception message, if possible
                var parenIndex = message.IndexOf(clockSkewMessageParen, StringComparison.Ordinal);
                if (parenIndex >= 0)
                {
                    parenIndex++;

                    // Locate " + " or " - " separator that follows the server time string
                    var separatorIndex = message.IndexOf(clockSkewMessagePlusSeparator, parenIndex, StringComparison.Ordinal);
                    if (separatorIndex < 0)
                    {
                        separatorIndex = message.IndexOf(clockSkewMessageMinusSeparator, parenIndex, StringComparison.Ordinal);
                    }

                    // Get the server time string and parse it
                    if (separatorIndex > parenIndex)
                    {
                        var timestamp = message.Substring(parenIndex, separatorIndex - parenIndex);
                        if (DateTime.TryParseExact(
                                timestamp,
                                AWSSDKUtils.ISO8601BasicDateTimeFormat,
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.AssumeUniversal,
                                out serverTime))
                        {
                            return(true);
                        }
                    }
                }
            }

            serverTime = DateTime.MinValue;
            return(false);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Detects if the signature is malformed, and the requested bucket is in a Region
        /// different from the Region of the request.
        /// </summary>
        /// <param name="requestedBucketUri"></param>
        /// <param name="serviceException"></param>
        /// <returns>the correct region if a mismatch was detected, null otherwise</returns>
        private static string GetCorrectRegion(AmazonS3Uri requestedBucketUri, AmazonServiceException serviceException)
        {
            string regionFromExceptionBody = null;
            string regionFromExceptionHeader = null;
            var s3Exception = serviceException as AmazonS3Exception;
            if (s3Exception != null)
            {
                if (string.Equals(s3Exception.ErrorCode, AuthorizationHeaderMalformedErrorCode, StringComparison.Ordinal))
                {
                    regionFromExceptionBody = CheckRegionAndUpdateCache(requestedBucketUri, s3Exception.Region);
                }

                if (regionFromExceptionBody == null)
                {
                    var innerException = s3Exception.InnerException as HttpErrorResponseException;
                    if (innerException != null && innerException.Response != null && innerException.Response.IsHeaderPresent(HeaderKeys.XAmzBucketRegion))
                    {
                        regionFromExceptionHeader = CheckRegionAndUpdateCache(requestedBucketUri, innerException.Response.GetHeaderValue(HeaderKeys.XAmzBucketRegion));
                    }
                }
            }
            return regionFromExceptionBody ?? regionFromExceptionHeader;
        }
Exemplo n.º 11
0
 private static bool TryParseExceptionMessage(AmazonServiceException ase, out DateTime serverTime)
 {
     if (ase != null && !string.IsNullOrEmpty(ase.Message))
     {
         string message = ase.Message;
         int    num     = message.IndexOf("(", StringComparison.Ordinal);
         if (num >= 0)
         {
             num++;
             int num2 = message.IndexOf(" + ", num, StringComparison.Ordinal);
             if (num2 < 0)
             {
                 num2 = message.IndexOf(" - ", num, StringComparison.Ordinal);
             }
             if (num2 > num && DateTime.TryParseExact(message.Substring(num, num2 - num), "yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out serverTime))
             {
                 return(true);
             }
         }
     }
     serverTime = DateTime.MinValue;
     return(false);
 }
Exemplo n.º 12
0
        private bool IsClockskew(IExecutionContext executionContext, Exception exception)
        {
            AmazonServiceException ex = exception as AmazonServiceException;
            bool num  = executionContext.RequestContext.Request != null && string.Equals(executionContext.RequestContext.Request.HttpMethod, "HEAD", StringComparison.Ordinal);
            bool flag = ex != null && (ex.ErrorCode == null || clockSkewErrorCodes.Contains(ex.ErrorCode));

            if (num | flag)
            {
                DateTime utcNow          = DateTime.UtcNow;
                DateTime correctedUtcNow = AWSSDKUtils.CorrectedUtcNow;
                DateTime serverTime;
                bool     flag2 = TryParseDateHeader(ex, out serverTime);
                if (!flag2)
                {
                    flag2 = TryParseExceptionMessage(ex, out serverTime);
                }
                if (flag2)
                {
                    serverTime = serverTime.ToUniversalTime();
                    TimeSpan timeSpan = correctedUtcNow - serverTime;
                    if (((timeSpan.Ticks < 0) ? (-timeSpan) : timeSpan) > clockSkewMaxThreshold)
                    {
                        TimeSpan timeSpan2 = serverTime - utcNow;
                        Logger.InfoFormat("Identified clock skew: local time = {0}, local time with correction = {1}, current clock skew correction = {2}, server time = {3}.", utcNow, correctedUtcNow, AWSConfigs.ClockOffset, serverTime);
                        AWSConfigs.ClockOffset = timeSpan2;
                        if (AWSConfigs.CorrectForClockSkew)
                        {
                            Logger.InfoFormat("Setting clock skew correction: new clock skew correction = {0}.", timeSpan2);
                            executionContext.RequestContext.IsSigned = false;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Detects if the signature is malformed, and the requested bucket is in a Region
 /// different from the Region of the request.
 /// </summary>
 /// <param name="requestedBucketUri"></param>
 /// <param name="serviceException"></param>
 /// <param name="credentials"></param>
 /// <returns>the correct region if a mismatch was detected, null otherwise</returns>
 internal static async Task<string> DetectMismatchWithHeadBucketFallbackAsync(AmazonS3Uri requestedBucketUri, AmazonServiceException serviceException, ImmutableCredentials credentials)
 {
     return GetCorrectRegion(requestedBucketUri, serviceException) ??
         CheckRegionAndUpdateCache(requestedBucketUri, await GetBucketRegionNoPipelineAsync(requestedBucketUri.Bucket, credentials));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Returns true if a failed request should be retried.
        /// </summary>
        /// <param name="statusCode">The HTTP status code from the failed request</param>
        /// <param name="config">The client config</param>
        /// <param name="errorResponseException">The exception from the failed request</param>
        /// <param name="retries">The number of times the current request has been attempted</param>
        /// <returns>True if the failed request should be retried.</returns>
        public static bool ShouldRetry(HttpStatusCode statusCode, ClientConfig config, AmazonServiceException errorResponseException, int retries)
        {
            if (retries > config.MaxErrorRetry)
            {
                return(false);
            }

            /*
             * For 500 internal server errors and 503 service
             * unavailable errors, we want to retry, but we need to use
             * an exponential back-off strategy so that we don't overload
             * a server with a flood of retries. If we've surpassed our
             * retry limit we handle the error response as a non-retryable
             * error and go ahead and throw it back to the user as an exception.
             */
            if (statusCode == HttpStatusCode.InternalServerError ||
                statusCode == HttpStatusCode.ServiceUnavailable)
            {
                return(true);
            }

            if (errorResponseException.InnerException is WebException &&
                (((WebException)(errorResponseException.InnerException)).Status == WebExceptionStatus.KeepAliveFailure))
            {
                return(true);
            }

            /*
             * Throttling is reported as a 400 or 503 error from services. To try and
             * smooth out an occasional throttling error, we'll pause and retry,
             * hoping that the pause is long enough for the request to get through
             * the next time.
             */
            if ((statusCode == HttpStatusCode.BadRequest || statusCode == HttpStatusCode.ServiceUnavailable) &&
                errorResponseException != null)
            {
                string errorCode = errorResponseException.ErrorCode;
                if (ErrorCodesToRetryOn.Contains(errorCode))
                {
                    return(true);
                }
            }

            return(false);
        }
        public override void Execute()
        {
            ValidateRequest();
            GetObjectRequest getRequest = ConvertToGetObjectRequest(this._request);

            var maxRetries = ((AmazonS3Client)_s3Client).Config.MaxErrorRetry;
            var retries = 0;
            bool shouldRetry = false;
            string mostRecentETag = null;
            do
            {
                shouldRetry = false;

                if (retries != 0)
                {
                    ByteRange bytesRemaining = ByteRangeRemainingForDownload(this._request.FilePath);
                    getRequest.ByteRange = bytesRemaining;
                }

                using (var response = this._s3Client.GetObject(getRequest))
                {
                    if (!string.IsNullOrEmpty(mostRecentETag) && !string.Equals(mostRecentETag, response.ETag))
                    {
                        AmazonServiceException eTagChanged = new AmazonServiceException("ETag changed during download retry.");
                        throw eTagChanged;
                    }
                    mostRecentETag = response.ETag;

                    try
                    {
                        if (retries == 0)
                        {
                            /* 
                             * Wipe the local file, if it exists, to handle edge case where:
                             * 
                             * 1. File foo exists
                             * 2. We start trying to download, but unsuccesfully write any data
                             * 3. We retry the download, with retires > 0, thus hitting the else statement below
                             * 4. We will append to file foo, instead of overwriting it
                             * 
                             * We counter it with the call below because it's the same call that would be hit
                             * in WriteResponseStreamToFile. If any exceptions are thrown, they will be the same as before
                             * to avoid any breaking changes to customers who handle that specific exception in a
                             * particular manor.
                             */
                            FileStream temp = new FileStream(this._request.FilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, Amazon.S3.Util.S3Constants.DefaultBufferSize);
                            temp.Close();

                            response.WriteObjectProgressEvent += OnWriteObjectProgressEvent;
                            response.WriteResponseStreamToFile(this._request.FilePath);
                        }
                        else
                        {
                            response.WriteObjectProgressEvent += OnWriteObjectProgressEvent;
                            response.WriteResponseStreamToFile(this._request.FilePath, true);
                        }
                    }
                    catch (Exception exception)
                    {
                        retries++;
                        shouldRetry = HandleException(exception, retries, maxRetries);
                        if (!shouldRetry)
                        {
                            if (exception is IOException)
                            {
                                throw;
                            }
                            else if (exception is AmazonServiceException ||
                                exception is AmazonClientException)
                            {
                                throw;
                            }
                            else
                            {
                                throw new AmazonServiceException(exception);
                            }
                        }
                    }
                }
                WaitBeforeRetry(retries);
            } while (shouldRetry);

        }
Exemplo n.º 16
0
        private bool HandleHttpWebErrorResponse(AsyncResult asyncResult, WebException we)
        {
            asyncResult.Metrics.AddProperty(Metric.Exception, we);

            HttpStatusCode         statusCode;
            AmazonServiceException errorResponseException = null;

            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
            {
                if (we != null && WebExceptionStatusesToThrowOn.Contains(we.Status))
                {
                    throw new AmazonServiceException("Encountered a non retryable WebException : " + we.Status, we);
                }

                if (httpErrorResponse == null ||
                    (we != null && WebExceptionStatusesToRetryOn.Contains(we.Status)))
                {
                    // Abort the unsuccessful request
                    asyncResult.RequestState.WebRequest.Abort();

                    if (CanRetry(asyncResult) && asyncResult.RetriesAttempt < Config.MaxErrorRetry)
                    {
                        pauseExponentially(asyncResult);
                        return(true);
                    }
                    var errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                     "Encountered a WebException ({0}), the request cannot be retried. Either the maximum number of retries has been exceeded ({1}/{2}) or the request is using a non-seekable stream.",
                                                     we.Status, asyncResult.RetriesAttempt, Config.MaxErrorRetry);
                    throw new AmazonServiceException(errorMessage, we);
                }

                statusCode = httpErrorResponse.StatusCode;
                asyncResult.Metrics.AddProperty(Metric.StatusCode, statusCode);
                string redirectedLocation = httpErrorResponse.Headers[HeaderKeys.LocationHeader];
                asyncResult.Metrics.AddProperty(Metric.RedirectLocation, redirectedLocation);

                using (httpErrorResponse)
                {
                    var unmarshaller                 = asyncResult.Unmarshaller;
                    var httpResponseData             = new HttpWebRequestResponseData(httpErrorResponse);
                    UnmarshallerContext errorContext = unmarshaller.CreateContext(httpResponseData,
                                                                                  Config.LogResponse || Config.ReadEntireResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never,
                                                                                  httpResponseData.ResponseBody.OpenResponse(),
                                                                                  asyncResult.Metrics);

                    errorResponseException = unmarshaller.UnmarshallException(errorContext, we, statusCode);
                    if (Config.LogResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never)
                    {
                        this.logger.Error(errorResponseException, "Received error response: [{0}]", errorContext.ResponseBody);
                    }
                    asyncResult.Metrics.AddProperty(Metric.AWSRequestID, errorResponseException.RequestId);
                    asyncResult.Metrics.AddProperty(Metric.AWSErrorCode, errorResponseException.ErrorCode);
                }
                asyncResult.RequestState.WebRequest.Abort();

                if (CanRetry(asyncResult))
                {
                    if (isTemporaryRedirect(statusCode, redirectedLocation))
                    {
                        this.logger.DebugFormat("Request {0} is being redirected to {1}.", asyncResult.RequestName, redirectedLocation);
                        asyncResult.Request.Endpoint = new Uri(redirectedLocation);
                        return(true);
                    }
                    else if (ShouldRetry(statusCode, this.Config, errorResponseException, asyncResult.RetriesAttempt))
                    {
                        this.logger.DebugFormat("Retry number {0} for request {1}.", asyncResult.RetriesAttempt, asyncResult.RequestName);
                        pauseExponentially(asyncResult);
                        return(true);
                    }
                }
            }

            if (errorResponseException != null)
            {
                this.logger.Error(errorResponseException, "Error making request {0}.", asyncResult.RequestName);
                throw errorResponseException;
            }

            AmazonServiceException excep = new AmazonServiceException("Unable to make request", we, statusCode);

            this.logger.Error(excep, "Error making request {0}.", asyncResult.RequestName);
            asyncResult.Metrics.AddProperty(Metric.Exception, excep);
            throw excep;
        }
        bool handleHttpWebErrorResponse(AsyncResult asyncResult, WebException we)
        {
            asyncResult.Metrics.AddProperty(RequestMetrics.Metric.Exception, we);

            HttpStatusCode         statusCode;
            AmazonServiceException errorResponseException = null;

            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
            {
                if (httpErrorResponse == null)
                {
                    // Abort the unsuccessful request
                    asyncResult.RequestState.WebRequest.Abort();

                    // If it is a keep alive error or name resolution error then attempt a retry
                    if (we != null && asyncResult.RetriesAttempt < config.MaxErrorRetry && (we.Status == WebExceptionStatus.KeepAliveFailure || we.Status == WebExceptionStatus.NameResolutionFailure))
                    {
                        pauseExponentially(asyncResult);
                        return(true);
                    }
                    throw new AmazonServiceException(we);
                }
                statusCode = httpErrorResponse.StatusCode;
                asyncResult.Metrics.AddProperty(RequestMetrics.Metric.StatusCode, statusCode);
                string redirectedLocation = httpErrorResponse.Headers["location"];
                asyncResult.Metrics.AddProperty(RequestMetrics.Metric.RedirectLocation, redirectedLocation);

                using (httpErrorResponse)
                {
                    var unmarshaller = asyncResult.Unmarshaller;
                    UnmarshallerContext errorContext = unmarshaller.CreateContext(httpErrorResponse, config.LogResponse || config.ReadEntireResponse || AWSConfigs.ResponseLogging != ResponseLoggingOption.Never, asyncResult);
                    errorResponseException = unmarshaller.UnmarshallException(errorContext, we, statusCode);
                    if (config.LogResponse || AWSConfigs.ResponseLogging != ResponseLoggingOption.Never)
                    {
                        logger.Error(errorResponseException, "Received error response: [{0}]", errorContext.ResponseBody);
                    }
                    asyncResult.Metrics.AddProperty(RequestMetrics.Metric.AWSRequestID, errorResponseException.RequestId);
                    asyncResult.Metrics.AddProperty(RequestMetrics.Metric.AWSErrorCode, errorResponseException.ErrorCode);
                }
                asyncResult.RequestState.WebRequest.Abort();

                if (isTemporaryRedirect(statusCode, redirectedLocation))
                {
                    asyncResult.Request.Endpoint = new Uri(redirectedLocation);
                    return(true);
                }
                else if (ShouldRetry(statusCode, this.config, errorResponseException, asyncResult.RetriesAttempt))
                {
                    pauseExponentially(asyncResult);
                    return(true);
                }
            }

            if (errorResponseException != null)
            {
                logger.Error(errorResponseException, "Error making request {0}.", asyncResult.RequestName);
                throw errorResponseException;
            }

            AmazonServiceException excep = new AmazonServiceException("Unable to make request", we, statusCode);

            logger.Error(excep, "Error making request {0}.", asyncResult.RequestName);
            asyncResult.Metrics.AddProperty(RequestMetrics.Metric.Exception, excep);
            throw excep;
        }
 /// <summary>Format and display an exception</summary>
 /// <param name="ex">Exception to display</param>
 private void ShowError(AmazonServiceException ex)
 {
     if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") || ex.ErrorCode.Equals("InvalidSecurity"))) {
         Project.Log(Level.Error, "Please check the provided AWS Credentials.");
         Project.Log(Level.Error, "If you haven't signed up for Amazon DynamoDB, please visit http://aws.amazon.com/dynamodb");
     } else {
         Project.Log(Level.Error, "An Error, number {0}, occurred with the message '{1}'",
             ex.ErrorCode, ex.Message);
     }
 }
Exemplo n.º 19
0
        private static bool TryParseExceptionMessage(AmazonServiceException ase, out DateTime serverTime)
        {
            var message = ase.Message;
            if (!string.IsNullOrEmpty(message))
            {
                // parse server time from exception message, if possible
                var parenIndex = message.IndexOf(clockSkewMessageParen, StringComparison.Ordinal);
                if (parenIndex >= 0)
                {
                    parenIndex++;

                    // Locate " + " or " - " separator that follows the server time string
                    var separatorIndex = message.IndexOf(clockSkewMessagePlusSeparator, parenIndex, StringComparison.Ordinal);
                    if (separatorIndex < 0)
                        separatorIndex = message.IndexOf(clockSkewMessageMinusSeparator, parenIndex, StringComparison.Ordinal);

                    // Get the server time string and parse it
                    if (separatorIndex > parenIndex)
                    {
                        var timestamp = message.Substring(parenIndex, separatorIndex - parenIndex);
                        if (DateTime.TryParseExact(
                                timestamp,
                                AWSSDKUtils.ISO8601BasicDateTimeFormat,
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.AssumeUniversal,
                                out serverTime))
                        {
                            return true;
                        }
                    }
                }
            }

            serverTime = DateTime.MinValue;
            return false;
        }
Exemplo n.º 20
0
        private static bool TryParseDateHeader(AmazonServiceException ase, out DateTime serverTime)
        {
            var webData = GetWebData(ase);

            if (webData != null)
            {
                // parse server time from "Date" header, if possible
                var dateValue = webData.GetHeaderValue(dateHeaderName);
                if (!string.IsNullOrEmpty(dateValue))
                {
                    if (DateTime.TryParseExact(
                            dateValue,
                            AWSSDKUtils.GMTDateFormat,
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.AssumeUniversal,
                            out serverTime))
                    {
                        return true;
                    }
                }
            }

            serverTime = DateTime.MinValue;
            return false;
        }
        private SyncManagerException HandleException(Exception e, string message)
        {
            var ase = e as AmazonServiceException;

            if (ase == null) ase = new AmazonServiceException(e);

            if (ase.GetType() == typeof(ResourceNotFoundException))
            {
                return new DatasetNotFoundException(message);
            }
            else if (ase.GetType() == typeof(ResourceConflictException)
                     || ase.StatusCode == System.Net.HttpStatusCode.Conflict)
            {
                return new DataConflictException(message);
            }
            else if (ase.GetType() == typeof(LimitExceededException))
            {
                return new DataLimitExceededException(message);
            }
            else if (IsNetworkException(ase))
            {
                return new NetworkException(message);
            }
            else
            {
                return new DataStorageException(message, ase);
            }
        }
Exemplo n.º 22
0
        private static IWebResponseData GetWebData(AmazonServiceException ase)
        {
            if (ase != null)
            {
                Exception e = ase;
                do
                {
                    var here = e as HttpErrorResponseException;
                    if (here != null)
                        return here.Response;
                    e = e.InnerException;
                } while (e != null);
            }

            return null;
        }
 private static bool IsNetworkException(AmazonServiceException ase)
 {
     return ase.InnerException != null && ase.InnerException.GetType() == typeof(IOException);
 }