Inheritance: Amazon.Runtime.AmazonServiceException
Example #1
0
 /// <summary>
 /// Constructs AmazonSQSException with message and wrapped exception
 /// </summary>
 /// <param name="message">Overview of error</param>
 /// <param name="t">Wrapped exception</param>
 public AmazonSQSException(String message, Exception t) : base(message, t)
 {
     this.message = message;
     if (t is AmazonSQSException)
     {
         AmazonSQSException ex = (AmazonSQSException)t;
         this.statusCode = ex.StatusCode;
         this.errorCode  = ex.ErrorCode;
         this.errorType  = ex.ErrorType;
         this.requestId  = ex.RequestId;
         this.xml        = ex.XML;
     }
 }
        public AmazonSQSException(string message, Exception innerException) : base(message, innerException)
        {
            this.message = message;
            AmazonSQSException exception = innerException as AmazonSQSException;

            if (exception != null)
            {
                this.statusCode = exception.StatusCode;
                this.errorCode  = exception.ErrorCode;
                this.errorType  = exception.ErrorType;
                this.requestId  = exception.RequestId;
                this.xml        = exception.XML;
            }
        }
Example #3
0
        /**
         * Look for additional error strings in the response and return formatted exception
         */
        private static AmazonSQSException ReportAnyErrors(string responseBody, HttpStatusCode status)
        {
            AmazonSQSException ex = null;

            if (responseBody != null && responseBody.StartsWith("<"))
            {
                Match errorMatcherOne = Regex.Match(
                    responseBody,
                    "<RequestId>(.*)</RequestId>.*<Error><Code>(.*)</Code><Message>(.*)</Message></Error>.*(<Error>)?",
                    RegexOptions.Multiline);
                Match errorMatcherTwo = Regex.Match(
                    responseBody,
                    "<Error><Code>(.*)</Code><Message>(.*)</Message></Error>.*(<Error>)?.*<RequestID>(.*)</RequestID>",
                    RegexOptions.Multiline);

                if (errorMatcherOne.Success)
                {
                    string requestId = errorMatcherOne.Groups[1].Value;
                    string code      = errorMatcherOne.Groups[2].Value;
                    string message   = errorMatcherOne.Groups[3].Value;

                    ex = new AmazonSQSException(message, status, code, "Unknown", requestId, responseBody);
                }
                else if (errorMatcherTwo.Success)
                {
                    string code      = errorMatcherTwo.Groups[1].Value;
                    string message   = errorMatcherTwo.Groups[2].Value;
                    string requestId = errorMatcherTwo.Groups[4].Value;

                    ex = new AmazonSQSException(message, status, code, "Unknown", requestId, responseBody);
                }
                else
                {
                    ex = new AmazonSQSException("Internal Error", status);
                }
            }
            else
            {
                ex = new AmazonSQSException("Internal Error", status);
            }
            return(ex);
        }
 private void amazonExceptionHandler(AmazonSQSException ex)
 {
     if(ex.ErrorCode.Equals("AWS.SimpleQueueService.NonExistentQueue"))
     {
         // Fatal Exception
         String message = "The specified queue does not exist.";
         log.Fatal(message);
         throw new ApplicationException(message, ex);
     }
     else if(ex.ErrorCode.Equals("AccessDenied"))
     {
         // Fatal Exception
         String message = "You do not have permission to read the queue.";
         log.Fatal(message);
         throw new ApplicationException(message, ex);
     }
     else
     {
         log.Warn("An unknown error has occurred.  Will retry.", ex);
     }
 }
Example #5
0
        /**
         * Invoke request and return response
         */
        private T Invoke <T>(IDictionary <String, String> parameters)
        {
            String actionName   = parameters["Action"];
            T      response     = default(T);
            String responseBody = null;
            String queueUrl     = parameters.ContainsKey("QueueUrl") ? parameters["QueueUrl"] : config.ServiceURL;

            if (parameters.ContainsKey("QueueUrl"))
            {
                parameters.Remove("QueueUrl");
            }
            HttpStatusCode statusCode = default(HttpStatusCode);

            /* Add required request parameters */
            AddRequiredParameters(parameters, queueUrl);

            String queryString = GetParametersAsString(parameters);

            byte[] requestData = new UTF8Encoding().GetBytes(queryString);
            bool   shouldRetry = true;
            int    retries     = 0;

            do
            {
                HttpWebRequest request = ConfigureWebRequest(requestData.Length, queueUrl);
                /* Submit the request and read response body */
                try
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(requestData, 0, requestData.Length);
                    }
                    using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse)
                    {
                        statusCode = httpResponse.StatusCode;
                        StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8);
                        responseBody = reader.ReadToEnd();
                    }

                    /* Attempt to deserialize response into <Action> Response type */
                    XmlSerializer serlizer = new XmlSerializer(typeof(T));
                    response    = (T)serlizer.Deserialize(new StringReader(responseBody));
                    shouldRetry = false;
                }
                /* Web exception is thrown on unsucessful responses */
                catch (WebException we)
                {
                    shouldRetry = false;
                    using (HttpWebResponse httpErrorResponse = (HttpWebResponse)we.Response as HttpWebResponse)
                    {
                        if (httpErrorResponse == null)
                        {
                            throw new AmazonSQSException(we);
                        }
                        statusCode = httpErrorResponse.StatusCode;
                        StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8);
                        responseBody = reader.ReadToEnd();
                    }

                    if (statusCode == HttpStatusCode.InternalServerError || statusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        shouldRetry = true;
                        PauseOnRetry(++retries, statusCode);
                    }
                    else
                    {
                        /* Attempt to deserialize response into ErrorResponse type */
                        try
                        {
                            XmlSerializer serlizer      = new XmlSerializer(typeof(ErrorResponse));
                            ErrorResponse errorResponse = (ErrorResponse)serlizer.Deserialize(new StringReader(responseBody));
                            Error         error         = errorResponse.Error[0];

                            /* Throw formatted exception with information available from the error response */
                            throw new AmazonSQSException(
                                      error.Message,
                                      statusCode,
                                      error.Code,
                                      error.Type,
                                      errorResponse.RequestId,
                                      errorResponse.ToXML());
                        }
                        /* Rethrow on deserializer error */
                        catch (Exception e)
                        {
                            if (e is AmazonSQSException)
                            {
                                throw e;
                            }
                            else
                            {
                                AmazonSQSException se = ReportAnyErrors(responseBody, statusCode, e);
                                throw se;
                            }
                        }
                    }
                }

                /* Catch other exceptions, attempt to convert to formatted exception,
                 * else rethrow wrapped exception */
                catch (Exception e)
                {
                    throw new AmazonSQSException(e);
                }
            } while (shouldRetry);

            return(response);
        }
Example #6
0
        /**
         * Invoke request and return response
         */
        private T Invoke <T>(IDictionary <string, string> parameters)
        {
            T      response = default(T);
            string queueUrl = parameters.ContainsKey("QueueUrl") ? parameters["QueueUrl"] : config.ServiceURL;

            if (parameters.ContainsKey("QueueUrl"))
            {
                parameters.Remove("QueueUrl");
            }
            HttpStatusCode statusCode = default(HttpStatusCode);

            /* Add required request parameters */
            AddRequiredParameters(parameters, queueUrl);

            string queryString = AWSSDKUtils.GetParametersAsString(parameters);
            bool   shouldRetry = true;
            int    retries     = 0;
            int    maxRetries  = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry;

            do
            {
                string         responseBody = string.Empty;
                HttpWebRequest request      = ConfigureWebRequest(queueUrl, queryString);
                /* Submit the request and read response body */
                try
                {
                    request.BeginGetResponse(asyncResponse =>
                    {
                        try
                        {
                            HttpWebResponse asyncResult = (HttpWebResponse)request.EndGetResponse(asyncResponse);
                            Stream streamResponse       = asyncResult.GetResponseStream();

                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                responseBody             = streamRead.ReadToEnd();
                                XDocument doc            = XDocument.Parse(responseBody);
                                XmlSerializer serializer = new XmlSerializer(typeof(T));
                                XmlReader xmlReader      = doc.CreateReader();
                                response = (T)serializer.Deserialize(xmlReader);
                                // Disposing StreamReader automatically closes the underlying streams
                            }

                            OnSQSResponse.Invoke(this, new ResponseEventArgs(response as ISQSResponse));
                        }
                        catch (WebException we)
                        {
                            shouldRetry = false;
                            using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
                            {
                                if (httpErrorResponse == null)
                                {
                                    // Abort the unsuccessful request
                                    request.Abort();
                                    throw;
                                }
                                statusCode = httpErrorResponse.StatusCode;
                                using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8))
                                {
                                    responseBody = reader.ReadToEnd();
                                }

                                // Abort the unsuccessful request
                                request.Abort();
                            }

                            if (statusCode == HttpStatusCode.InternalServerError ||
                                statusCode == HttpStatusCode.ServiceUnavailable)
                            {
                                shouldRetry = true;
                                PauseOnRetry(++retries, maxRetries, statusCode);
                            }
                            else
                            {
                                AmazonSQSException amazonException = null;
                                /* Attempt to deserialize response into ErrorResponse type */
                                try
                                {
                                    XDocument doc = XDocument.Parse(responseBody);
                                    using (XmlReader sr = doc.CreateReader())
                                    {
                                        XmlSerializer serializer    = new XmlSerializer(typeof(ErrorResponse));
                                        ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr);
                                        Error error = errorResponse.Error.ElementAt(0);

                                        ///* Throw formatted exception with information available from the error response */
                                        amazonException = new AmazonSQSException(
                                            error.Message,
                                            statusCode,
                                            error.Code,
                                            error.Type,
                                            errorResponse.RequestId,
                                            errorResponse.ToXML()
                                            );
                                        throw amazonException;
                                    }
                                }
                                /* Rethrow on deserializer error */
                                catch (Exception e)
                                {
                                    if (e is AmazonSQSException)
                                    {
                                        if (null != OnSQSResponse)
                                        {
                                            OnSQSResponse.Invoke(this, new ResponseEventArgs(amazonException));
                                        }
                                    }
                                    else
                                    {
                                        if (null != OnSQSResponse)
                                        {
                                            OnSQSResponse.Invoke(this, new ResponseEventArgs(ReportAnyErrors(responseBody, statusCode)));
                                        }
                                    }
                                }
                            }
                        }
                    }, request);

                    shouldRetry = false;
                }

                /* Catch other exceptions, attempt to convert to formatted exception,
                 * else rethrow wrapped exception */
                catch (Exception)
                {
                    // Abort the unsuccessful request
                    request.Abort();
                    throw;
                }
            } while (shouldRetry);

            return(response);
        }
Example #7
0
        void SQSErrorResponse(AmazonSQSException error)
        {
            StringBuilder errorBuilder = new StringBuilder();
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "ERROR CODE: {0}", error.ErrorCode));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "ERROR TYPE: {0}", error.ErrorType));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "INNER EXCEPTION: {0}", error.InnerException));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "MESSAGE: {0}", error.Message));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "REQUEST ID: {0}", error.RequestId));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "STATUS CODE: {0}", error.StatusCode));
            errorBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "\nERROR RESPONSE:\n {0}", error.XML));

            this.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(errorBuilder.ToString(), "Error Occured", MessageBoxButton.OK);
            });
        }