public void Should_pass_on_exception_when_getting_hearings_by_username_for_deletion_fails() { _bookingsApiClient.Setup(x => x.GetHearingsByUsernameForDeletionAsync(It.IsAny <string>())) .ThrowsAsync(ClientException.ForBookingsAPI(HttpStatusCode.InternalServerError)); Assert.ThrowsAsync <BookingsApiException>(() => _controller.GetHearingsByUsernameForDeletionAsync("*****@*****.**")); }
private Exception GetExceptionToBeLogged(Exception ex) { ClientException cex = ex as ClientException; SqlException sqlEx = ex as SqlException; RawClientException rcex = ex as RawClientException; if (sqlEx != null && sqlEx.Number == -2) { cex = new ClientException(ClientExceptionId.SqlTimeout); } if (cex != null) { if (ConfigurationMapper.Instance.LogHandledExceptions) { return(ex); } else if (cex.InnerException != null) { return(cex.InnerException); } } else if (rcex != null && ConfigurationMapper.Instance.LogHandledExceptions) { return(ex); } //if its an unhandled exception return(ex); }
public void GetCredentials3() { // When Credentials will Expired // Mock Response var response = new HttpResponse(); var ExpiredDatetime = DateTime.Now.AddMilliseconds(800).ToString(); var content = Encoding.GetEncoding("UTF-8").GetBytes( "{\"Code\":\"Success\",\"Message\":\"ThisIsMessage\",\"RequestId\":\"ThisIsRequestId\",\"AccessKeyId\":\"MockAccessKeyId\",\"AccessKeySecret\":\"\",\"SecurityToken\":\"\",\"Expiration\":\"" + ExpiredDatetime + "\"}"); response.ContentType = FormatType.JSON; response.Content = content; response.Status = 200; // Mock Credentials var mockCredentials = new Mock <InstanceProfileCredentials>("MockAccessKeyId", "", "", ExpiredDatetime, 100000) { CallBase = true }; mockCredentials.Setup(foo => foo.RemainTicks()).Returns(15 * 1000 * 1000 * 10); var instanceProfileCredentials = mockCredentials.Object; // Mock Fetcher var mockFetcher = new Mock <ECSMetadataServiceCredentialsFetcher> { CallBase = true }; mockFetcher.Setup(foo => foo.GetResponse( It.IsAny <HttpRequest>() )).Returns(response); mockFetcher.Setup(foo => foo.Fetch()).Returns(instanceProfileCredentials); var fetcher = mockFetcher.Object; var roleName = ACKMock.GetRoleName(true); var instance = new InstanceProfileCredentialsProvider(roleName); AlibabaCloudCredentialsProvider provider = instance; instance.withFetcher(fetcher); // Throw exception if the date is invalid var credentials = provider.GetCredentials(); // When Fetcher throw ClientException mockFetcher = new Mock <ECSMetadataServiceCredentialsFetcher> { CallBase = true }; var ex = new ClientException("MockClientExceptionCode", "MockClinetExceptionMessage"); mockFetcher.Setup(foo => foo.Fetch()).Throws(ex); fetcher = mockFetcher.Object; instance.withFetcher(fetcher); credentials = provider.GetCredentials(); Assert.Equal("MockAccessKeyId", credentials.GetAccessKeyId()); }
public void BatchResponseContent_InitializeWithNullResponseMessage() { ClientException ex = Assert.Throws <ClientException>(() => new BatchResponseContent(null)); Assert.Equal(ErrorConstants.Codes.InvalidArgument, ex.Error.Code); Assert.Equal(string.Format(ErrorConstants.Messages.NullParameter, "httpResponseMessage"), ex.Error.Message); }
public static Neo4jException ParseServerException(string code, string message) { Neo4jException error; var parts = code.Split('.'); var classification = parts[1].ToLowerInvariant(); switch (classification) { case "clienterror": if (AuthenticationException.IsAuthenticationError(code)) { error = new AuthenticationException(message); } else if (ProtocolException.IsProtocolError(code)) { error = new ProtocolException(code, message); } else { error = new ClientException(code, message); } break; case "transienterror": error = new TransientException(code, message); break; default: error = new DatabaseException(code, message); break; } return(error); }
// Detects of any exceptions have occured and throws the appropriate exceptions. protected internal virtual void DetectError(HTTPClient client) { ResponseException exception = null; string reason = string.Format("{0} {1}", StatusCode, ReasonPhrase); if (StatusCode >= 500) { exception = new ServerException(this, new Exception(reason)); } else if (StatusCode == 404) { exception = new NotFoundException(this, new Exception(reason)); } else if (StatusCode == 401) { exception = new AuthenticationException(this, new Exception(reason)); } else if (StatusCode >= 400) { exception = new ClientException(this, new Exception(reason)); } else if (!Parsed) { exception = new ParserException(this, new Exception(reason)); } if (exception != null) { exception.Log(client.Configuration, this); throw exception; } }
/*[ActionName("Index")] public ActionResult SegundaSolapa() * { * ViewBag.Error = TempData["Error"]; * int idUsuario = Convert.ToInt16(this.Session["IdUsuario"]); * var quienMeContrato = cs.traerQuienesMeContrataron(idUsuario); * * return View(quienMeContrato); * }*/ public ActionResult Contratar(Publicacion publicacion) { int idUsuario = Convert.ToInt16(this.Session["IdUsuario"]); var usuario = us.ObtenerUsuarioEditar(idUsuario); if (publicacion.IdUsuario == idUsuario) //Significa que el usuario que publico es el mismo que inicio sesion { TempData["Error"] = "No podes contratar tu publicación."; return(RedirectToAction("Index")); } else { try { var contratacion = cs.nuevaContratacion(publicacion, usuario); TempData["Exito"] = "Contratación exitosa."; return(RedirectToAction("Index")); } catch (Exception ex) { ClientException.LogException(ex, "Error al contratar la publicación."); return(RedirectToAction("Error", "Shared")); } } }
public ActionResult CambiarFotoPerfil(HttpPostedFileBase file) { string extension = Path.GetExtension(file.FileName); int id = Convert.ToInt16(this.Session["IdUsuario"]); if (file != null && file.ContentLength > 0 && extension == ".jpg") { try { string uniqueFileName = Path.ChangeExtension("imagen", Convert.ToString(id)); string path = Path.Combine(Server.MapPath("~/Imagenes/FotoPerfil"), Path.GetFileName(uniqueFileName + extension)); file.SaveAs(path); TempData["Exito"] = "Tu foto de perfil se ha cargado con éxito."; return(RedirectToAction("Home", "Home")); } catch (Exception ex) { ClientException.LogException(ex, "Error al cargar la imágen."); return(RedirectToAction("Error", "Shared")); } } else { TempData["Error"] = "No se pudo cargar la imagen, intentalo nuevamente."; return(RedirectToAction("EditarPerfil", new { id = id })); } }
internal static string GetMessageFromException(Exception ex) { string errorDetails = ex.Message; FaceAPIException faceApiException = ex as FaceAPIException; if (faceApiException?.ErrorMessage != null) { errorDetails = faceApiException.ErrorMessage; } ClientException commonException = ex as ClientException; if (commonException?.Error?.Message != null) { errorDetails = commonException.Error.Message; } Microsoft.ProjectOxford.Vision.ClientException visionException = ex as Microsoft.ProjectOxford.Vision.ClientException; if (visionException?.Error?.Message != null) { errorDetails = visionException.Error.Message; } return(errorDetails); }
public ActionResult Preguntar(int idUsuario, int id, string preguntar) { int idUser = Convert.ToInt16(this.Session["IdUsuario"]); if (idUsuario == idUser) { TempData["Error"] = "No podes preguntar en tu publicación."; return(RedirectToAction("VisualizarPublicacion", "Publicacion", new { idPublicacion = id })); } else { if (!string.IsNullOrWhiteSpace(preguntar)) { try { prs.PreguntarEnPublicacion(idUser, id, preguntar); TempData["Exito"] = "Pregunta publicada correctamente."; return(RedirectToAction("VisualizarPublicacion", "Publicacion", new { idPublicacion = id })); } catch (Exception ex) { ClientException.LogException(ex, "Error al guardar la pregunta."); return(RedirectToAction("Error", "Shared")); } } TempData["Error"] = "La pregunta no puede ser vacía."; return(RedirectToAction("VisualizarPublicacion", "Publicacion", new { idPublicacion = id })); } }
/// <summary> /// Called when [exeption occured]. /// </summary> private static void OnExceptionOccured(object sender, ClientException e) { MessageBox.Show(e.DisplayText + "\r\n\r\n" + ExceptionPrinter.Print(e), e.Message, MessageBoxButton.OK, MessageBoxImage.Error); Execute.BeginOnUIThread(() => Application.Current.Shutdown(2)); }
// Detects of any exceptions have occured and throws the appropriate exceptions. internal void detectError() { ResponseException exception = null; if (statusCode >= 500) { exception = new ServerException(this); } else if (statusCode == 404) { exception = new NotFoundException(this); } else if (statusCode == 401) { exception = new AuthenticationException(this); } else if (statusCode >= 400) { exception = new ClientException(this); } else if (!parsed) { exception = new ParserException(this); } if (exception != null) { throw exception; } }
public ClientException BadRequest(string message) { ClientException result = ClientException.BadRequest(message); return(result); // TODO: add assertions to method ClientExceptionTest.BadRequest(String) }
public void TestRetryOnException() { var product = "ecs"; var version = "2014-05-26"; var apiName = "DescribeInstances"; ClientException exception = null; var retryPolicyContext = new RetryPolicyContext(exception, "200", 1, product, version, apiName, RetryCondition.BlankStatus); var retryOnApiCondition = new RetryOnExceptionCondition(); var shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.NoRetry, shouldRetry); exception = new ClientException("SDK.HttpError", "TestMessage"); retryPolicyContext = new RetryPolicyContext(exception, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.ShouldRetry, shouldRetry); var serverException = new ServerException("InternalError", "TestMessage"); retryPolicyContext = new RetryPolicyContext(serverException, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.ShouldRetry, shouldRetry); product = "vpc"; serverException = new ServerException("Throttling", "TestMessage"); retryPolicyContext = new RetryPolicyContext(serverException, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.NoRetry, shouldRetry); product = "ecs"; serverException = new ServerException("ThrottlingTest", "TestMessage"); retryPolicyContext = new RetryPolicyContext(serverException, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.NoRetry | RetryCondition.ShouldRetryWithThrottlingBackoff, shouldRetry); serverException = new ServerException("Throttling", "TestMessage"); retryPolicyContext = new RetryPolicyContext(serverException, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.ShouldRetry | RetryCondition.ShouldRetryWithThrottlingBackoff, shouldRetry); var clientException = new ClientException("TestCode", "TestNullMessage"); retryPolicyContext = new RetryPolicyContext(clientException, "200", 1, product, version, apiName, RetryCondition.BlankStatus); shouldRetry = retryOnApiCondition.ShouldRetry(retryPolicyContext); Assert.Equal(RetryCondition.NoRetry, shouldRetry); }
public void Should_throw_exception_when_add_user_to_group_has_null_user_name() { _userApiClient.Setup(x => x.AddUserToGroupAsync(It.IsAny <AddUserToGroupRequest>())) .Throws(ClientException.ForUserService(HttpStatusCode.InternalServerError)); Assert.ThrowsAsync <UserApiException>(() => _service.AssignParticipantToGroup(null, "Individual")); }
public void ShouldErrorOnSummary() { var exc = new ClientException("some error"); var cursor = CreateFailingResultCursor(exc); var result = new InternalRxResult(Observable.Return(cursor)); VerifyError(result.Consume(), exc); }
public void Should_return_a_not_found_when_invalid_username_is_passed() { _userAccountService.Setup(x => x.ResetParticipantPassword(It.IsAny <string>())) .ThrowsAsync(ClientException.ForUserService(HttpStatusCode.NotFound)); var response = _controller.ResetPassword("*****@*****.**"); response.Result.Should().BeOfType <NotFoundObjectResult>(); }
public void Should_return_a_bad_request_when_no_username_is_passed() { _userAccountService.Setup(x => x.ResetParticipantPassword(It.IsAny <string>())) .ThrowsAsync(ClientException.ForUserService(HttpStatusCode.BadRequest)); var response = _controller.ResetPassword(""); response.Result.Should().BeOfType <BadRequestObjectResult>(); }
public void ShouldErrorOnRecords() { var exc = new ClientException("some error"); var cursor = CreateFailingResultCursor(exc); var result = new RxResult(Observable.Return(cursor)); VerifyError(result.Records(), exc); }
public void should_throw_exception_when_username_not_found_throws() { _userApiClient.Setup(x => x.GetUserByAdUserIdAsync(It.IsAny <string>())) .Throws(ClientException.ForUserService(HttpStatusCode.InternalServerError)); Assert.ThrowsAsync <UserApiException>(() => _service.GetAdUserIdForUsername("123")); }
public void Should_return_throw_when_booking_api_throws() { _bookingsApiClient.Setup(x => x.SearchForHearingsAsync(It.IsAny <string>(), It.IsAny <DateTimeOffset>())) .ThrowsAsync(ClientException.ForBookingsAPI(HttpStatusCode.InternalServerError)); Assert.ThrowsAsync <BookingsApiException>(() => _controller.SearchForAudioRecordedHearingsAsync("bad", DateTime.Today)); }
public void ShouldErrorOnSummary() { var failure = new ClientException("some error"); var cursor = CreateFailingResultCursor(failure, 2, 5); var result = new RxResult(Observable.Return(cursor)); VerifyError(result.Consume(), failure); }
public void Should_fail_if_we_cannot_figure_out_user_existence() { _userApiClient.Setup(x => x.GetUserByEmailAsync(It.IsAny <string>())) .Throws(ClientException.ForUserService(HttpStatusCode.InternalServerError)); Assert.ThrowsAsync <UserApiException>(() => _service.UpdateParticipantUsername(new BookingsApi.Contract.Requests.ParticipantRequest())); }
public void Instance1() { ClientException exception = new ClientException("200", "message", "requestId"); Assert.Equal("200", exception.ErrorCode); Assert.Equal("message", exception.ErrorMessage); Assert.Null(exception.RequestId); }
internal static Exception SmsClientError(string cause, ClientException ex) { SmsException exception = new SmsException(AliyunErrorCodes.SmsClientError, ex); exception.Data["Cause"] = cause; return(exception); }
public void Instance3() { ClientException exception = new ClientException(""); Assert.Null(exception.ErrorMessage); Assert.Null(exception.ErrorCode); Assert.Null(exception.RequestId); }
public async Task Should_pass_on_bad_request_from_bookings_api() { _bookingsApiClient.Setup(x => x.PostPersonBySearchTermAsync(It.IsAny <SearchTermRequest>())) .ThrowsAsync(ClientException.ForBookingsAPI(HttpStatusCode.BadRequest)); var response = await _controller.PostPersonBySearchTerm("term"); response.Result.Should().BeOfType <BadRequestObjectResult>(); }
public void ShouldErrorOnSummaryRepeatable() { var failure = new ClientException("some error"); var cursor = CreateFailingResultCursor(failure, 2, 5); var result = new InternalRxStatementResult(Observable.Return(cursor)); VerifyError(result.Summary(), failure); VerifyError(result.Summary(), failure); }
public void ClientException_properties_are_set() { var e = new ClientException(ClientException.FailureReason.UnknownError, Message, InnerException); VerifyException(e); Assert.That(e.Reason, Is.EqualTo(ClientException.FailureReason.UnknownError)); }
public ActionResult RegistrarUsuario(string nombre, string apellido, string dni, string mail, string telefono, string contrasenia, string CaptchaCode, string geocomplete) { bool estado = bool.Parse(Request.Form.GetValues("ckbAcepto")[0]); if (ModelState.IsValid && estado == true && !string.IsNullOrWhiteSpace(geocomplete)) { if (us.UsuarioDadoDeBaja(mail)) { ModelState.AddModelError("", "El usuario registrado con esa direccion de correo electronico fue dado de baja."); return(View()); } else { if (us.UsuarioExisteActivado(mail, dni)) { ModelState.AddModelError("", "La direccion de correo electrónico o el DNI ingresado ya posee una cuenta asociada."); return(View()); } else { if (us.UsuarioExisteInactivo(mail, dni)) { try { us.ActivarUsuarioInactivo(nombre, apellido, dni, mail, telefono, contrasenia, geocomplete); } catch (System.Net.Mail.SmtpException ex) { ClientException.LogException(ex, "Error al enviar el mail de activación."); return(RedirectToAction("Error", "Shared")); } } else { try { us.AgregarUsuarioNuevo(nombre, apellido, dni, mail, telefono, contrasenia, geocomplete); } catch (System.Net.Mail.SmtpException ex) { ClientException.LogException(ex, "Error al enviar el mail de activación."); return(RedirectToAction("Error", "Shared")); } } TempData["Exito"] = "La registración fue exitosa. Revisa tu correo electrónico para activar la cuenta."; return(RedirectToAction("IniciarSesion")); } } } else { ModelState.AddModelError("", "No te olvides de ingresar ubicación, y aceptar los términos y condiciones para continuar con la registración."); return(View()); } }