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)); } }
private void ProcessException(AmazonServiceException ex, Entity subsegment) { int statusCode = (int)ex.StatusCode; var responseAttributes = new Dictionary <string, object>(); if (statusCode >= 400 && statusCode <= 499) { _recorder.MarkError(); if (statusCode == 429) { _recorder.MarkThrottle(); } } else if (statusCode >= 500 && statusCode <= 599) { _recorder.MarkFault(); } responseAttributes["status"] = statusCode; _recorder.AddHttpInformation("response", responseAttributes); subsegment.Aws["request_id"] = ex.RequestId; // AmazonId2 property in AmazonS3Exception corresponds to the x-amz-id-2 Http header var property = ex.GetType().GetProperty("AmazonId2"); if (property != null) { subsegment.Aws["id_2"] = (string)property.GetValue(ex, null); } }
private bool RetryForExceptionSync(Exception exception) { if (exception is IOException) { if (IsInnerException <ThreadAbortException>(exception)) { return(false); } return(true); } AmazonServiceException ex = exception as AmazonServiceException; if (ex != null) { if (HttpStatusCodesToRetryOn.Contains(ex.StatusCode)) { return(true); } if (ex.StatusCode == HttpStatusCode.BadRequest || ex.StatusCode == HttpStatusCode.ServiceUnavailable) { string errorCode = ex.ErrorCode; if (ErrorCodesToRetryOn.Contains(errorCode)) { return(true); } } if (IsInnerException(exception, out WebException inner) && WebExceptionStatusesToRetryOn.Contains(inner.Status)) { return(true); } } return(false); }
/// <summary> /// Shared logic for the HandleException and HandleExceptionAsync /// </summary> /// <param name="requestContext"></param> /// <param name="httpErrorResponse"></param> /// <param name="exception"></param> /// <param name="responseStream"></param> /// <returns></returns> private bool HandleExceptionStream(IRequestContext requestContext, IWebResponseData httpErrorResponse, HttpErrorResponseException exception, System.IO.Stream responseStream) { requestContext.Metrics.AddProperty(Metric.StatusCode, httpErrorResponse.StatusCode); AmazonServiceException errorResponseException = null; // Unmarshall the service error response and throw the corresponding service exception. try { var unmarshaller = requestContext.Unmarshaller; var readEntireResponse = true; var errorContext = unmarshaller.CreateContext(httpErrorResponse, readEntireResponse, responseStream, requestContext.Metrics, true, requestContext); try { errorResponseException = unmarshaller.UnmarshallException(errorContext, exception, httpErrorResponse.StatusCode); } catch (Exception e) { // Rethrow Amazon service or client exceptions if (e is AmazonServiceException || e is AmazonClientException) { throw; } // Else, there was an issue with the response body, throw AmazonUnmarshallingException var requestId = httpErrorResponse.GetHeaderValue(HeaderKeys.RequestIdHeader); var body = errorContext.ResponseBody; throw new AmazonUnmarshallingException(requestId, lastKnownLocation: null, responseBody: body, innerException: e, statusCode: httpErrorResponse.StatusCode); } requestContext.Metrics.AddProperty(Metric.AWSRequestID, errorResponseException.RequestId); requestContext.Metrics.AddProperty(Metric.AWSErrorCode, errorResponseException.ErrorCode); var logResponseBody = requestContext.ClientConfig.LogResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never; if (logResponseBody) { this.Logger.Error(errorResponseException, "Received error response: [{0}]", errorContext.ResponseBody); } } catch (Exception unmarshallException) { this.Logger.Error(unmarshallException, "Failed to unmarshall a service error response."); throw; } throw errorResponseException; }
private static void CatchAmazonSnsException(AmazonServiceException e, ILogger logger) { logger.LogError(() => $"Error Code: {e.ErrorCode}"); logger.LogError(() => $"Error Type: {e.ErrorType}"); logger.LogError(() => $"Request ID: {e.RequestId}"); logger.LogError(() => $"HTTP Status Code: {e.StatusCode}"); throw new Exception(); }
public async Task Execute_HaveOCCExceptionsAndAbortFailuresWithinRetryLimit_Succeeded() { var mockCreator = new Mock <Func <Task <Session> > >(); var mockSession = new Mock <Session>(null, null, null, null, null); mockCreator.Setup(x => x()).ReturnsAsync(mockSession.Object); var retry = new Mock <Func <int, Task> >(); var sendCommandResponseStart = new StartTransactionResult { TransactionId = "testTransactionIdddddd" }; var h1 = QldbHash.ToQldbHash("testTransactionIdddddd"); var sendCommandResponseCommit = new CommitTransactionResult { CommitDigest = new MemoryStream(h1.Hash), TransactionId = "testTransactionIdddddd" }; var abortResponse = new AbortTransactionResult { }; var serviceException = new AmazonServiceException(); mockSession.Setup(x => x.StartTransaction(It.IsAny <CancellationToken>())) .ReturnsAsync(sendCommandResponseStart); mockSession.Setup(x => x.CommitTransaction(It.IsAny <string>(), It.IsAny <MemoryStream>(), It.IsAny <CancellationToken>())) .ReturnsAsync(sendCommandResponseCommit); mockSession.SetupSequence(x => x.AbortTransaction(It.IsAny <CancellationToken>())) .ThrowsAsync(serviceException) .ReturnsAsync(abortResponse) .ThrowsAsync(serviceException); var mockFunction = new Mock <Func <TransactionExecutor, Task <int> > >(); mockFunction.SetupSequence(f => f.Invoke(It.IsAny <TransactionExecutor>())) .ThrowsAsync(new OccConflictException("occ")) .ThrowsAsync(new OccConflictException("occ")) .ThrowsAsync(new OccConflictException("occ")) .ReturnsAsync(1); var mockRetry = new Mock <Action <int> >(); var pool = new SessionPool(mockCreator.Object, QldbDriverBuilder.CreateDefaultRetryHandler(NullLogger.Instance), 2, NullLogger.Instance); var session1 = await pool.GetSession(); var session2 = await pool.GetSession(); session1.Release(); session2.Release(); await pool.Execute(mockFunction.Object, Driver.RetryPolicy.Builder().Build(), retry.Object); mockCreator.Verify(x => x(), Times.Exactly(2)); retry.Verify(r => r.Invoke(It.IsAny <int>()), Times.Exactly(3)); Assert.AreEqual(2, pool.AvailablePermit()); }
/// <summary> /// Get the potentially useful inner web exception message if there is one. /// </summary> /// <param name="exception"></param> /// <returns></returns> public static string GetWebExceptionMessage(this AmazonServiceException exception) { return((exception.InnerException as WebException)? .Response? .GetResponseStream()? .Map(stream => new StreamReader(stream).ReadToEnd()) .Map(message => "An exception was thrown while contacting the AWS API.\n" + message) ?? "An exception was thrown while contacting the AWS API."); }
private void ProcessException(ExceptionTelemetry telemetry, AmazonServiceException ex) { int statusCode = (int)ex.StatusCode; telemetry.Properties["resultCode"] = statusCode.ToString(); telemetry.Properties["request_id"] = ex.RequestId; telemetry.Properties["aws http status"] = ((int)ex.StatusCode).ToString(); telemetry.Properties["aws http errorCode"] = ex.ErrorCode; }
/// <summary> /// Handles an exception for the given execution context. /// </summary> /// <param name="executionContext">The execution context, it contains the /// request and response context.</param> /// <param name="exception">The exception to handle.</param> /// <returns> /// Returns a boolean value which indicates if the original exception /// should be rethrown. /// This method can also throw a new exception to replace the original exception. /// </returns> public override bool HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) { var requestContext = executionContext.RequestContext; var responseContext = executionContext.ResponseContext; var httpErrorResponse = exception.Response; // If 404 was suppressed and successfully unmarshalled, // don't rethrow the original exception. if (HandleSuppressed404(executionContext, httpErrorResponse)) { return(false); } requestContext.Metrics.AddProperty(Metric.StatusCode, httpErrorResponse.StatusCode); AmazonServiceException errorResponseException = null; // Unmarshall the service error response and throw the corresponding service exception. try { using (httpErrorResponse.ResponseBody) { var unmarshaller = requestContext.Unmarshaller; var readEntireResponse = requestContext.ClientConfig.LogResponse || requestContext.ClientConfig.ReadEntireResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never; var errorContext = unmarshaller.CreateContext(httpErrorResponse, readEntireResponse, httpErrorResponse.ResponseBody.OpenResponse(), requestContext.Metrics); errorResponseException = unmarshaller.UnmarshallException(errorContext, exception, httpErrorResponse.StatusCode); Debug.Assert(errorResponseException != null); requestContext.Metrics.AddProperty(Metric.AWSRequestID, errorResponseException.RequestId); requestContext.Metrics.AddProperty(Metric.AWSErrorCode, errorResponseException.ErrorCode); var logResponseBody = requestContext.ClientConfig.LogResponse || AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never; if (logResponseBody) { this.Logger.Error(errorResponseException, "Received error response: [{0}]", errorContext.ResponseBody); } } } catch (Exception unmarshallException) { this.Logger.Error(unmarshallException, "Failed to unmarshall a service error response."); throw; } throw errorResponseException; }
/// <summary> /// The AmazonServiceException can hold additional information that is useful to include in /// the log. /// </summary> /// <param name="exception">The exception</param> private void HandleAmazonServiceException(AmazonServiceException exception) { ((exception.InnerException as WebException)? .Response? .GetResponseStream()? .Map(stream => new StreamReader(stream).ReadToEnd()) .Map(message => "An exception was thrown while contacting the AWS API.\n" + message) ?? "An exception was thrown while contacting the AWS API.") .Tee(message => DisplayWarning("AWS-S3-ERROR-0001", message)); }
private static void ConsoleError(AmazonServiceException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Caught AWS Exception: " + ex.Message); Console.WriteLine("Response Status Code: " + ex.StatusCode); Console.WriteLine("Error Code: " + ex.ErrorCode); Console.WriteLine("Error Type: " + ex.ErrorType); Console.WriteLine("Request ID: " + ex.RequestId); Console.ForegroundColor = ConsoleColor.White; }
public void GetSession_FailedToCreateSession_ThrowTheOriginalException() { var mockCreator = new Mock <Func <Session> >(); var exception = new AmazonServiceException("test"); mockCreator.Setup(x => x()).Throws(exception); var pool = new SessionPool(mockCreator.Object, QldbDriverBuilder.CreateDefaultRetryHandler(NullLogger.Instance), 1, NullLogger.Instance); Assert.ThrowsException <AmazonServiceException>(() => pool.GetSession()); }
private System.Exception HandleAmazonServiceException(AmazonServiceException ex) { _logger.LogError(ex, ex.Message, ex.StatusCode); throw ex.StatusCode switch { HttpStatusCode.NotFound => new FileNotFoundException(ex.Message, ex), // TODO: discuss with Team. not handled by exception Middleware HttpStatusCode.BadRequest => new ArgumentException(ex.Message, ex), _ => new TechnicalException($"An AWS S3 error occurred: {ex.Message}, status code: {ex.StatusCode}", ex) }; }
private static Exception ConvertAmazonException(AmazonServiceException e, string name) { switch (e.StatusCode) { case HttpStatusCode.NotFound: return(new StorageFileNotFoundException($"Could not find file '{name}'", e)); default: return(new StorageException( $"Failed to access file '{name}', examine inner exception for details.", e)); } }
public async Task TestDDBScanUnsuccessful() #endif { var processor = new Mock <BaseProcessor <Activity> >(); var parent = new Activity("parent").Start(); using (Sdk.CreateTracerProviderBuilder() .SetSampler(new AlwaysOnSampler()) .AddXRayTraceId() .AddAWSInstrumentation() .AddProcessor(processor.Object) .Build()) { var ddb = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1); string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere"; AmazonServiceException amazonServiceException = new AmazonServiceException(); amazonServiceException.StatusCode = System.Net.HttpStatusCode.NotFound; amazonServiceException.RequestId = requestId; CustomResponses.SetResponse(ddb, (request) => { throw amazonServiceException; }); var scan_request = new ScanRequest(); scan_request.TableName = "SampleProduct"; scan_request.AttributesToGet = new List <string>() { "Id", "Name" }; try { #if NET452 ddb.Scan(scan_request); #else await ddb.ScanAsync(scan_request); #endif } catch (AmazonServiceException) { var count = processor.Invocations.Count; Assert.Equal(3, count); Activity awssdk_activity = (Activity)processor.Invocations[2].Arguments[0]; this.ValidateAWSActivity(awssdk_activity, parent); this.ValidateDynamoActivityTags(awssdk_activity); Assert.Equal(requestId, Utils.GetTagValue(awssdk_activity, "aws.requestId")); Assert.Equal(Status.Error.WithDescription("Exception of type 'Amazon.Runtime.AmazonServiceException' was thrown."), awssdk_activity.GetStatus()); Assert.Equal("exception", awssdk_activity.Events.First().Name); } } }
/// <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); } }
public override AmazonServiceException UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode) { JsonUnmarshallerContext jsonUnmarshallerContext = input as JsonUnmarshallerContext; if (jsonUnmarshallerContext == null) { throw new InvalidOperationException("Unsupported UnmarshallerContext"); } AmazonServiceException ex = UnmarshallException(jsonUnmarshallerContext, innerException, statusCode); ex.RequestId = jsonUnmarshallerContext.ResponseData.GetHeaderValue("x-amzn-RequestId"); return(ex); }
/// <summary> /// Handles an exception for the given execution context. /// </summary> /// <param name="executionContext">The execution context, it contains the /// request and response context.</param> /// <param name="exception">The exception to handle.</param> /// <returns> /// Returns a boolean value which indicates if the original exception /// should be rethrown. /// This method can also throw a new exception to replace the original exception. /// </returns> public override bool HandleException(IExecutionContext executionContext, UnityHttpErrorResponseException exception) { LogCurlRequest(exception.Request); var requestContext = executionContext.RequestContext; var httpErrorResponse = exception.Response; var errorResponse = new ErrorResponse(); if (httpErrorResponse.IsHeaderPresent(HeaderKeys.XAmzRequestIdHeader)) { errorResponse.RequestId = httpErrorResponse.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader); requestContext.Metrics.AddProperty(Metric.AWSRequestID, httpErrorResponse.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader)); } if (httpErrorResponse.IsHeaderPresent(HeaderKeys.XAmzErrorTypeHeader)) { errorResponse.Code = httpErrorResponse.GetHeaderValue(HeaderKeys.XAmzErrorTypeHeader); } if (httpErrorResponse.IsHeaderPresent(HeaderKeys.XAmzErrorMessageHeader)) { errorResponse.Message = httpErrorResponse.GetHeaderValue(HeaderKeys.XAmzErrorMessageHeader); } if (httpErrorResponse.IsHeaderPresent(HeaderKeys.XAmzId2Header)) { requestContext.Metrics.AddProperty(Metric.AmzId2, httpErrorResponse.GetHeaderValue(HeaderKeys.XAmzId2Header)); } requestContext.Metrics.AddProperty(Metric.StatusCode, httpErrorResponse.StatusCode); Exception unmarshalledException = null; var unmarshaller = requestContext.Unmarshaller as ISimplifiedErrorUnmarshaller; if (unmarshaller != null) { unmarshalledException = unmarshaller.UnmarshallException(httpErrorResponse, errorResponse, exception); LogErrorMessage(unmarshalledException, errorResponse); throw unmarshalledException; } else { var baseServiceException = new AmazonServiceException(); baseServiceException.RequestId = errorResponse.RequestId; baseServiceException.ErrorCode = errorResponse.Code; baseServiceException.StatusCode = httpErrorResponse.StatusCode; throw baseServiceException; } }
public override bool HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) { IRequestContext requestContext = executionContext.RequestContext; IWebResponseData response = exception.Response; if (HandleSuppressed404(executionContext, response)) { return(false); } requestContext.Metrics.AddProperty(Metric.StatusCode, response.StatusCode); AmazonServiceException ex = null; try { using (response.ResponseBody) { ResponseUnmarshaller unmarshaller = requestContext.Unmarshaller; bool readEntireResponse = true; UnmarshallerContext unmarshallerContext = unmarshaller.CreateContext(response, readEntireResponse, response.ResponseBody.OpenResponse(), requestContext.Metrics); try { ex = unmarshaller.UnmarshallException(unmarshallerContext, exception, response.StatusCode); } catch (Exception ex2) { if (ex2 is AmazonServiceException || ex2 is AmazonClientException) { throw; } string headerValue = response.GetHeaderValue("x-amzn-RequestId"); string responseBody = unmarshallerContext.ResponseBody; throw new AmazonUnmarshallingException(headerValue, null, responseBody, ex2); } requestContext.Metrics.AddProperty(Metric.AWSRequestID, ex.RequestId); requestContext.Metrics.AddProperty(Metric.AWSErrorCode, ex.ErrorCode); if (requestContext.ClientConfig.LogResponse || AWSConfigs.LoggingConfig.LogResponses != 0) { base.Logger.Error(ex, "Received error response: [{0}]", unmarshallerContext.ResponseBody); } } } catch (Exception exception2) { base.Logger.Error(exception2, "Failed to unmarshall a service error response."); throw; } throw ex; }
public async Task TestAsyncGetSession_FailedToCreateSession_ThrowTheOriginalException() { var exception = new AmazonServiceException("test"); mockClient.QueueResponse(exception); try { await testDriver.GetSession(CancellationToken.None); Assert.Fail("driver.GetSession() should have thrown retriable exception"); } catch (RetriableException re) { Assert.IsNotNull(re.InnerException); Assert.AreEqual(exception, re.InnerException); } }
public void TestGetSession_FailedToCreateSession_ThrowTheOriginalException() { var exception = new AmazonServiceException("test"); mockClient.QueueResponse(exception); try { testDriver.GetSession(); Assert.Fail("driver.GetSession() should have thrown retriable exception"); } catch (RetriableException re) { Assert.IsNotNull(re.InnerException); Assert.AreEqual(exception, re.InnerException); } }
public void TestLowLevelAPIErrorCaseWrongCognitoCred() { List <Amazon.MobileAnalytics.Model.Event> listEvent = new List <Amazon.MobileAnalytics.Model.Event>(); listEvent.Add(BuildCustomEvent()); AmazonMobileAnalyticsClient client = new AmazonMobileAnalyticsClient(new CognitoAWSCredentials("wrong-cognito-pool-id", RegionEndpoint.USEast1), RegionEndpoint.USEast1); AmazonServiceException ase = null; try { AutoResetEvent ars = new AutoResetEvent(false); client.PutEventsAsync(new PutEventsRequest() { Events = listEvent, ClientContext = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(BuildClientContext())), ClientContextEncoding = "base64" }, (response) => { ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); } // TODO: is it the correct behavior that the exception is thrown from the PutEventsAsync call // rather than passed as response.Exception? catch (Exception exception) { if (exception is AmazonServiceException) { ase = exception as AmazonServiceException; } } Assert.IsNotNull(ase); // Ignoring this assertion as there seems to be some differences in the iOS // WWW implementation that gives us a status code 0. //Assert.AreEqual(HttpStatusCode.BadRequest, ase.StatusCode); Assert.AreEqual(ase.ErrorCode, "ValidationException"); }
public async Task TestExceptionHandlerAsyncForAWSSDKHandler() { using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1)) { string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere"; AmazonServiceException amazonServiceException = new AmazonServiceException(); amazonServiceException.StatusCode = System.Net.HttpStatusCode.NotFound; amazonServiceException.RequestId = requestId; CustomResponses.SetResponse(client, (request) => { throw amazonServiceException; }); _recorder.BeginSegment("test", TraceId); var segment = TraceContext.GetEntity(); try { await client.GetItemAsync( "test", new Dictionary <string, AttributeValue>() { { "invalid_key", new AttributeValue("1") } }); Assert.Fail(); } catch (AmazonServiceException e) { Assert.ReferenceEquals(e, segment.Subsegments[0].Cause.ExceptionDescriptors[0].Exception); Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("table_name")); Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("consistent_read")); Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("projection_expression")); Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("attribute_names_substituted")); var responseInfo = segment.Subsegments[0].Http["response"] as Dictionary <string, object>; Assert.AreEqual(404, responseInfo["status"]); var subsegment = segment.Subsegments[0]; Assert.AreEqual(requestId, subsegment.Aws["request_id"]); Assert.IsTrue(subsegment.HasError); Assert.IsFalse(subsegment.HasFault); } finally { _recorder.EndSegment(); } } }
private void ProcessException(ExceptionTelemetry telemetry, AmazonServiceException ex) { int statusCode = (int)ex.StatusCode; var responseAttributes = new Dictionary <string, object>(); if (statusCode >= 400 && statusCode <= 499) { if (statusCode == 429) { telemetry.Properties["Throttle"] = "true"; } } else if (statusCode >= 500 && statusCode <= 599) { } telemetry.Properties["resultCode"] = statusCode.ToString(); telemetry.Properties["request_id"] = ex.RequestId; telemetry.Properties["aws http status"] = ((int)ex.StatusCode).ToString(); telemetry.Properties["aws http errorCode"] = ex.ErrorCode; }
public bool?RetryForExceptionSync(IExecutionContext executionContext, Exception exception) { AmazonServiceException val = exception as AmazonServiceException; if (val != null) { if (val.get_StatusCode() == HttpStatusCode.OK) { Type type = ((object)executionContext.get_RequestContext().get_OriginalRequest()).GetType(); if (RequestsWith200Error.Contains(type)) { return(true); } } if (val.get_StatusCode() == HttpStatusCode.BadRequest) { if (new Uri(executionContext.get_RequestContext().get_ClientConfig().DetermineServiceURL()).Host.Equals("s3.amazonaws.com") && (((Exception)val).Message.Contains("AWS4-HMAC-SHA256") || ((Exception)val).Message.Contains("AWS KMS managed keys require AWS Signature Version 4"))) { this.get_Logger().InfoFormat("Request {0}: the bucket you are attempting to access should be addressed using a region-specific endpoint. Additional calls will be made to attempt to determine the correct region to be used. For better performance configure your client to use the correct region.", new object[1] { executionContext.get_RequestContext().get_RequestName() }); IRequest request = executionContext.get_RequestContext().get_Request(); AmazonS3Uri amazonS3Uri = new AmazonS3Uri(request.get_Endpoint()); string uriString = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}", amazonS3Uri.Bucket, "s3-external-1.amazonaws.com"); request.set_Endpoint(new Uri(uriString)); if (((Exception)val).Message.Contains("AWS KMS managed keys require AWS Signature Version 4")) { request.set_UseSigV4(true); request.set_AuthenticationRegion(RegionEndpoint.USEast1.get_SystemName()); executionContext.get_RequestContext().set_IsSigned(false); } return(true); } return(null); } } return(this.RetryForException(executionContext, exception)); }
public void SimplePathPutObjectTest() { var exception = new AmazonServiceException(); var mre = new AutoResetEvent(false); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, FilePath = relativeFilePath, CannedACL = S3CannedACL.AuthenticatedRead }; PutObjectResponse response = null; Client.PutObjectAsync(request, (result) => { exception = result.Exception as AmazonServiceException; response = result.Response; mre.Set(); }, options); mre.WaitOne(); Assert.IsNull(exception); Assert.IsTrue(response.ETag.Length > 0); }
public void TestLowLevelAPIErrorCaseWrongCognitoCred() { List <Amazon.MobileAnalytics.Model.Event> listEvent = new List <Amazon.MobileAnalytics.Model.Event>(); listEvent.Add(BuildCustomEvent()); PutEventsRequest putRequest = new PutEventsRequest(); putRequest.Events = listEvent; string clientContext = BuildClientContext(); Console.WriteLine("client context is {0}", clientContext); putRequest.ClientContext = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(clientContext)); putRequest.ClientContextEncoding = "base64"; PutEventsResponse PutResponse = null; AmazonServiceException exception = null; AmazonMobileAnalyticsClient client = new AmazonMobileAnalyticsClient(new CognitoAWSCredentials("wrong-cognito-pool-id", RegionEndpoint.USEast1), RegionEndpoint.USEast1); try { PutResponse = client.PutEventsAsync(putRequest).Result; } catch (AggregateException ae) { foreach (var e in ae.InnerExceptions) { if (e is AmazonServiceException) { exception = e as AmazonServiceException; break; } } } Assert.IsNotNull(exception); Assert.AreEqual(exception.StatusCode, HttpStatusCode.BadRequest); Assert.AreEqual(exception.ErrorCode, "ValidationException"); }
public void SimplePutObjectTest() { var exception = new AmazonServiceException(); var mre = new AutoResetEvent(false); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = "contentBodyPut" + random.Next(), ContentBody = testContent, CannedACL = S3CannedACL.AuthenticatedRead }; PutObjectResponse response = null; Client.PutObjectAsync(request, (result) => { exception = result.Exception as AmazonServiceException; response = result.Response; mre.Set(); }, options); mre.WaitOne(); Assert.IsTrue(response.ETag.Length > 0); }
private void ProcessException(AmazonServiceException ex, Entity subsegment) { int statusCode = (int)ex.StatusCode; var responseAttributes = new Dictionary <string, object>(); if (statusCode >= 400 && statusCode <= 499) { _recorder.MarkError(); if (statusCode == 429) { _recorder.MarkThrottle(); } } else if (statusCode >= 500 && statusCode <= 599) { _recorder.MarkFault(); } responseAttributes["status"] = statusCode; _recorder.AddHttpInformation("response", responseAttributes); subsegment.Aws["request_id"] = ex.RequestId; }
private static string GetCorrectRegion(AmazonS3Uri requestedBucketUri, AmazonServiceException serviceException) { string text = null; string text2 = null; AmazonS3Exception ex = serviceException as AmazonS3Exception; if (ex != null) { if (string.Equals(ex.get_ErrorCode(), "AuthorizationHeaderMalformed", StringComparison.Ordinal)) { text = CheckRegionAndUpdateCache(requestedBucketUri, ex.Region); } if (text == null) { HttpErrorResponseException val = ((Exception)ex).InnerException as HttpErrorResponseException; if (val != null && val.get_Response() != null && val.get_Response().IsHeaderPresent("x-amz-bucket-region")) { text2 = CheckRegionAndUpdateCache(requestedBucketUri, val.get_Response().GetHeaderValue("x-amz-bucket-region")); } } } return(text ?? text2); }