public void ConstructorTest()
        {
            var name = "TestName_ConstructorTest";

            var exception = new GoogleApiException(name, "Test");
            Assert.IsInstanceOf<Exception>(exception);
            Assert.That(exception.ToString(), Contains.Substring(name));
        }
        public void ConstructorTest()
        {
            var service = new MockService();

            var exception = new GoogleApiException(service, "Test");
            Assert.IsInstanceOf<Exception>(exception);
            Assert.That(exception.Service, Is.EqualTo(service));
            Assert.That(exception.ToString(), Contains.Substring(service.Name));
        }
示例#3
0
        public static SkillException HandleGoogleAPIException(GoogleApiException ex)
        {
            var skillExceptionType = SkillExceptionType.Other;

            if (ex.Error.Message.Equals(APIErrorAccessDenied, StringComparison.InvariantCultureIgnoreCase))
            {
                skillExceptionType = SkillExceptionType.APIAccessDenied;
            }

            return(new SkillException(skillExceptionType, ex.Message, ex));
        }
示例#4
0
        private void ProcessMemberResponse <T>(string id, T item, bool ignoreExistingMember, bool ignoreMissingMember, RequestError error, HttpResponseMessage message, Dictionary <string, ClientServiceRequest <T> > requestsToRetry, ClientServiceRequest <T> request, List <string> failedMembers, List <Exception> failures)
        {
            string memberKey;
            string memberRole = string.Empty;

            Member member = item as Member;

            if (member == null)
            {
                memberKey = item as string ?? "unknown";
            }
            else
            {
                memberKey  = member.Email ?? member.Id;
                memberRole = member.Role;
            }

            string requestType = request.GetType().Name;

            if (error == null)
            {
                Trace.WriteLine($"{requestType}: Success: Member: {memberKey}, Role: {memberRole}, Group: {id}");
                return;
            }

            string errorString = $"{error}\nFailed {requestType}: {memberKey}\nGroup: {id}";

            Trace.WriteLine($"{requestType}: Failed: Member: {memberKey}, Role: {memberRole}, Group: {id}\n{error}");

            if (ignoreExistingMember && this.IsExistingMemberError(message.StatusCode, errorString))
            {
                return;
            }

            if (ignoreMissingMember && this.IsMissingMemberError(message.StatusCode, errorString))
            {
                return;
            }

            if (ApiExtensions.IsRetryableError(message.StatusCode, errorString))
            {
                Trace.WriteLine($"Queuing {requestType} of {memberKey} from group {id} for backoff/retry");
                requestsToRetry.Add(memberKey, request);
                return;
            }

            GoogleApiException ex = new GoogleApiException("admin", errorString);

            ex.HttpStatusCode = message.StatusCode;
            failedMembers.Add(memberKey);
            failures.Add(ex);
        }
示例#5
0
 public bool GetMessageFromException(Exception ex, SdtMessages_Message msg)
 {
     try
     {
         GoogleApiException gex = (GoogleApiException)ex;
         msg.gxTpr_Id = gex.HttpStatusCode.ToString(); //should be the Status Code https://github.com/google/google-api-dotnet-client/issues/899
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        protected static GoogleApiException GerarExcecaoDeDuplicidadeDoGoogle()
        {
            var googleDuplicidadeException = new GoogleApiException(string.Empty, GoogleApiExceptionMensagens.Erro409EntityAlreadyExists);

            googleDuplicidadeException.HttpStatusCode = HttpStatusCode.Conflict;
            googleDuplicidadeException.Error          = new Google.Apis.Requests.RequestError
            {
                Code    = (int)HttpStatusCode.Conflict,
                Message = GoogleApiExceptionMensagens.Erro409EntityAlreadyExists
            };

            return(googleDuplicidadeException);
        }
示例#7
0
        public static bool IsAuthorizationError(GoogleApiException zException)
        {
            // REFERENCE: https://developers.google.com/doubleclick-advertisers/core_errors#UNAUTHORIZED
            if (zException.Error != null &&
                zException.Error.Errors.Count > 0)
            {
                var zError = zException.Error.Errors.FirstOrDefault(error =>
                                                                    ERROR_LOCATION_AUTHORIZATION.Equals(error.Location, StringComparison.InvariantCultureIgnoreCase));
                return(zError != null);
            }

            return(false);
        }
示例#8
0
        public void TestErrorDeserialization(
            [Values(DiscoveryVersion.Version_0_3, DiscoveryVersion.Version_1_0)] DiscoveryVersion version)
        {
            const string ErrorResponse =
                @"{
                    ""error"": {
                        ""errors"": [
                            {
                                ""domain"": ""global"",
                                ""reason"": ""required"",
                                ""message"": ""Required"",
                                ""locationType"": ""parameter"",
                                ""location"": ""resource.longUrl""
                            }
                        ],
                        ""code"": 400,
                        ""message"": ""Required""
                    }
                }";

            IService impl = CreateService(version);

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse)))
            {
                // Verify that the response is decoded correctly.
                GoogleApiException ex = Assert.Throws <GoogleApiException>(() =>
                {
                    impl.DeserializeResponse <MockJsonSchema>(new MockResponse()
                    {
                        Stream = stream
                    });
                });
                // Check that the contents of the error json was translated into the exception object.
                // We cannot compare the entire exception as it depends on the implementation and might change.
                Assert.That(ex.ToString(), Contains.Substring("resource.longUrl"));
            }

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse)))
            {
                RequestError error = impl.DeserializeError(new MockResponse()
                {
                    Stream = stream
                });
                Assert.AreEqual(400, error.Code);
                Assert.AreEqual("Required", error.Message);
                Assert.AreEqual(1, error.Errors.Count);
            }
        }
        /// <summary>
        /// Throws <see cref="GoogleApiException"/> if there were insert errors.
        /// The excetpion will contain details of these errors.
        /// </summary>
        /// <exception cref="GoogleApiException">There were insert errors.</exception>
        public BigQueryInsertResults ThrowOnAnyError()
        {
            if (_errors.Count == 0)
            {
                return(this);
            }

            var exception = new GoogleApiException(_client.Service.Name, $"Error inserting data. Status: {Status}")
            {
                Error = new RequestError
                {
                    Errors = Errors.SelectMany(rowErrors => rowErrors).ToList()
                }
            };

            throw exception;
        }
        public void Download_Error_JsonResponse()
        {
            var downloadUri = "http://www.sample.com";
            var chunkSize   = 100;
            var error       = new RequestError {
                Code = 12345, Message = "Text", Errors = new[] { new SingleError {
                                                                     Message = "Nested error"
                                                                 } }
            };
            var response = new StandardResponse <object> {
                Error = error
            };
            var responseText = new NewtonsoftJsonSerializer().Serialize(response);

            var handler = new MultipleChunksMessageHandler {
                ErrorResponse = responseText
            };

            handler.StatusCode = HttpStatusCode.BadRequest;
            handler.ChunkSize  = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList <IDownloadProgress> progressList = new List <IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException)lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(error.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message));
            }
        }
        private async Task Valida_Tratamento_De_Duplicidade_No_Google_Deve_Devolver_A_GoogleApiExption_Disparada()
        {
            // Arrange
            var funcionario = new FuncionarioEol(123456, "José da Silva", string.Empty, string.Empty);

            mediator.Setup(a => a.Send(It.IsAny <ExisteFuncionarioPorRfQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(false);

            var googleException = new GoogleApiException(string.Empty, "Erro no Google Classroom.");

            mediator.Setup(a => a.Send(It.IsAny <InserirFuncionarioGoogleCommand>(), It.IsAny <CancellationToken>()))
            .Throws(googleException);

            var funcionarioJson = JsonConvert.SerializeObject(funcionario);
            var mensagem        = new MensagemRabbit(funcionarioJson);

            // Assert
            await Assert.ThrowsAsync <GoogleApiException>(() => inserirFuncionarioGoogleUseCase.Executar(mensagem));
        }
 private void HandleInsertAllResponse(TableDataInsertAllResponse response)
 {
     if (response.InsertErrors != null)
     {
         var exception = new GoogleApiException(Service.Name, "Error inserting data")
         {
             Error = new RequestError
             {
                 Errors = response.InsertErrors
                          .SelectMany(errors => (errors.Errors ?? Enumerable.Empty <ErrorProto>()).Select(error => new SingleError
                 {
                     Location = error.Location,
                     Reason   = error.Reason,
                     Message  = $"Row {errors.Index}: {error.Message}"
                 }))
                          .ToList()
             }
         };
         throw exception;
     }
 }
示例#13
0
        private async Task Valida_Tratamento_De_Duplicidade_No_Google_Deve_Retornar_True()
        {
            // Arrange
            var aluno = new AlunoEol(1, "José da Silva", string.Empty, string.Empty, new DateTime(1990, 9, 10));
            var alunoComEmailTratado = new AlunoEol(1, "José da Silva", string.Empty, string.Empty, new DateTime(1990, 9, 10));

            mediator.Setup(a => a.Send(It.IsAny <VerificarEmailExistenteAlunoQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(alunoComEmailTratado);

            mediator.Setup(a => a.Send(It.IsAny <ExisteAlunoPorCodigoQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(false);

            var googleDuplicidadeException = new GoogleApiException(string.Empty, GoogleApiExceptionMensagens.Erro409EntityAlreadyExists);

            googleDuplicidadeException.HttpStatusCode = HttpStatusCode.Conflict;
            googleDuplicidadeException.Error          = new Google.Apis.Requests.RequestError
            {
                Code    = (int)HttpStatusCode.Conflict,
                Message = GoogleApiExceptionMensagens.Erro409EntityAlreadyExists
            };

            mediator.Setup(a => a.Send(It.IsAny <InserirAlunoGoogleCommand>(), It.IsAny <CancellationToken>()))
            .Throws(googleDuplicidadeException);

            mediator.Setup(a => a.Send(It.IsAny <IncluirUsuarioCommand>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(10);

            mediator.Setup(a => a.Send(It.IsAny <PublicaFilaRabbitCommand>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(true);

            var alunoJson = JsonConvert.SerializeObject(aluno);
            var mensagem  = new MensagemRabbit(alunoJson);

            // Act
            var retorno = await incluirAlunoUseCase.Executar(mensagem);

            // Assert
            Assert.True(retorno);
        }
        public void Download_Error_PlaintextResponse()
        {
            using (var service = new MockClientService())
            {
                var downloader = new MediaDownloader(service);
                IList <IDownloadProgress> progressList = new List <IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(_httpPrefix + "NotFoundPlainText", outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException)lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(HttpStatusCode.NotFound));
                Assert.That(exception.Message, Is.EqualTo(NotFoundError));
                Assert.IsNull(exception.Error);
            }
        }
示例#15
0
        public void TestErrorAddGceInstance()
        {
            const string psDiskVar = "attachedDisk";

            Pipeline.Runspace.SessionStateProxy.SetVariable(psDiskVar, new AttachedDisk());
            Mock <InstancesResource> instances    = ServiceMock.Resource(s => s.Instances);
            GoogleApiException       apiException = new GoogleApiException("mock-service-name", "mock-error-message");

            apiException.HttpStatusCode = HttpStatusCode.Conflict;

            instances.SetupRequestError <InstancesResource, InstancesResource.InsertRequest, Operation>(
                i => i.Insert(It.IsAny <Instance>(), It.IsAny <string>(), It.IsAny <string>()),
                apiException);

            Pipeline.Commands.AddScript(
                $"Add-GceInstance -Name instance-name -Disk ${psDiskVar}");
            Collection <PSObject> results = Pipeline.Invoke();

            // An error should be thrown (if it is a terminating error,
            // we wouldn't even reach this point).
            TestErrorRecord(ErrorCategory.ResourceExists);
        }
示例#16
0
        private void ProcessStudentResponse <T>(string id, string studentKey, bool ignoreExistingStudent, bool ignoreMissingStudent, RequestError error, HttpResponseMessage message, Dictionary <string, ClientServiceRequest <T> > requestsToRetry, ClientServiceRequest <T> request, List <string> failedStudents, List <Exception> failures)
        {
            string requestType = request.GetType().Name;

            if (error == null)
            {
                Trace.WriteLine($"{requestType}: Success: Student: {studentKey}, Course: {id}");
                return;
            }

            string errorString = $"{error}\nFailed {requestType}: {studentKey}\nCourse: {id}";

            Trace.WriteLine($"{requestType}: Failed: Student: {studentKey}, Course: {id}\n{error}");

            if (ignoreExistingStudent && this.IsExistingStudentError(message.StatusCode, errorString))
            {
                return;
            }

            if (ignoreMissingStudent && this.IsMissingStudentError(message.StatusCode, errorString))
            {
                return;
            }

            if (ApiExtensions.IsRetryableError(message.StatusCode, errorString))
            {
                Trace.WriteLine($"Queuing {requestType} of student {studentKey} from course {id} for backoff/retry");
                requestsToRetry.Add(studentKey, request);
                return;
            }

            GoogleApiException ex = new GoogleApiException("admin", errorString)
            {
                HttpStatusCode = message.StatusCode
            };

            failedStudents.Add(studentKey);
            failures.Add(ex);
        }
示例#17
0
        private async Task Valida_Tratamento_De_Excecoes_Do_Google_Deve_Devolver_A_GoogleApiExption_Disparada()
        {
            // Arrange
            var aluno = new AlunoEol(1, "José da Silva", string.Empty, string.Empty, new DateTime(1990, 9, 10));
            var alunoComEmailTratado = new AlunoEol(1, "José da Silva", string.Empty, string.Empty, new DateTime(1990, 9, 10));

            mediator.Setup(a => a.Send(It.IsAny <VerificarEmailExistenteAlunoQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(alunoComEmailTratado);

            mediator.Setup(a => a.Send(It.IsAny <ExisteAlunoPorCodigoQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(false);

            var googleDuplicidadeException = new GoogleApiException(string.Empty, "Erro no Google Classroom.");

            mediator.Setup(a => a.Send(It.IsAny <InserirAlunoGoogleCommand>(), It.IsAny <CancellationToken>()))
            .Throws(googleDuplicidadeException);

            var alunoJson = JsonConvert.SerializeObject(aluno);
            var mensagem  = new MensagemRabbit(alunoJson);

            // Assert
            await Assert.ThrowsAsync <GoogleApiException>(() => incluirAlunoUseCase.Executar(mensagem));
        }
        public static SkillException HandleGoogleAPIException(GoogleApiException ex)
        {
            var skillExceptionType = SkillExceptionType.Other;

            if (ex.Error.Message.Equals(APIErrorAccessDenied, StringComparison.InvariantCultureIgnoreCase))
            {
                skillExceptionType = SkillExceptionType.APIAccessDenied;
            }
            else if (ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                skillExceptionType = SkillExceptionType.APIUnauthorized;
            }
            else if (ex.HttpStatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                skillExceptionType = SkillExceptionType.APIForbidden;
            }
            else if (ex.HttpStatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                skillExceptionType = SkillExceptionType.APIBadRequest;
            }

            return(new SkillException(skillExceptionType, ex.Message, ex));
        }
 private void HandleInsertAllResponse(TableDataInsertAllResponse response, InsertOptions options)
 {
     var errors = response.InsertErrors;
     bool shouldThrow = options == null || !options.SuppressInsertErrors;
     if (errors?.Count > 0 && shouldThrow)
     {
         var exception = new GoogleApiException(Service.Name, "Error inserting data")
         {
             Error = new RequestError
             {
                 Errors = response.InsertErrors
                     .SelectMany(rowErrors => (rowErrors.Errors ?? Enumerable.Empty<ErrorProto>()).Select(error => new SingleError
                     {
                         Location = error.Location,
                         Reason = error.Reason,
                         Message = $"Row {rowErrors.Index}: {error.Message}"
                     }))
                     .ToList()
             }
         };
         throw exception;
     }
 }
        public void Download_Error_JsonResponse()
        {
            using (var service = new MockClientService())
            {
                var downloader = new MediaDownloader(service);
                IList <IDownloadProgress> progressList = new List <IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(_httpPrefix + "BadRequestJson", outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException)lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(BadRequestError.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(BadRequestError.Errors[0].Message));
            }
        }
        public void Download_Error_PlaintextResponse()
        {
            var downloadUri  = "http://www.sample.com";
            var chunkSize    = 100;
            var responseText = "Not Found";

            var handler = new MultipleChunksMessageHandler {
                ErrorResponse = responseText
            };

            handler.StatusCode = HttpStatusCode.NotFound;
            handler.ChunkSize  = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList <IDownloadProgress> progressList = new List <IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException)lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                Assert.That(exception.Message, Is.EqualTo(responseText));
                Assert.IsNull(exception.Error);
            }
        }
 public static bool IsAccessDenied(this GoogleApiException e)
 => e.Error != null && e.Error.Code == 403;
示例#23
0
 /// <summary>
 /// Initializes a new instance of the BigQueryExcpetion class with the specified settings.
 /// </summary>
 /// <param name="message">The message describing the current exception.</param>
 /// <param name="innerException">A GoogleApiException object representing.</param>
 public BigQueryException(string message, GoogleApiException innerException) : base(message, innerException)
 {
 }
示例#24
0
 public static bool EhErroDeDuplicidade(this GoogleApiException googleApiException)
 => googleApiException.Error?.Code == (int)HttpStatusCode.Conflict && googleApiException.Error.Message.ToLower().Contains(GoogleApiExceptionMensagens.Erro409EntityAlreadyExists.ToLower());
示例#25
0
 public static bool EmailContaServicoInvalido(this GoogleApiException googleApiException)
 => googleApiException.Error?.Code == (int)HttpStatusCode.BadRequest && googleApiException.Error.Message.ToLower().Contains(GoogleApiExceptionMensagens.Erro400InvalidGrant.ToLower());
示例#26
0
 public static bool AcessoNaoAutorizado(this GoogleApiException googleApiException)
 => googleApiException.Error?.Code == (int)HttpStatusCode.Forbidden && googleApiException.Error.Message.ToLower().Contains(GoogleApiExceptionMensagens.Erro403NotAuthorizedToAccess.ToLower());
示例#27
0
 public static bool RegistroNaoEncontrado(this GoogleApiException googleApiException)
 => googleApiException.Error?.Code == (int)HttpStatusCode.NotFound && (googleApiException.Error.Message.ToLower().Contains(GoogleApiExceptionMensagens.Erro404NotFound.ToLower()) || googleApiException.Error.Message.ToLower().Contains(GoogleApiExceptionMensagens.Erro404EntityNotFound.ToLower()));
 public static BigQueryException Wrap(this GoogleApiException exception)
 {
     return(new BigQueryException(exception.Message, exception));
 }
 public static bool IsBadRequest(this GoogleApiException e)
 => e.Error != null && e.Error.Code == 400 && e.Error.Message == "BAD REQUEST";
 public static bool IsConstraintViolation(this GoogleApiException e)
 => e.Error != null && e.Error.Code == 412;
 public static bool IsNotFound(this GoogleApiException e)
 => e.Error != null && e.Error.Code == 404;
示例#32
0
 public DataSourceException(string message, Exception innerException) : base(message, innerException)
 {
     InnerGoogleApiException = innerException as GoogleApiException;
 }