public static ErrorResponseException FromHttpRequestException(HttpRequestException exception) { var ex = new ErrorResponseException(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable), exception.Message, exception.InnerException) { ResponseString = exception.Message, }; foreach (var key in exception.Data.Keys) { ex.Data[key] = exception.Data[key]; } return(ex); }
public async Task UseCallback_CallbackThrowsSpecificException_SpecificExceptionPropagatesAsBaseException() { var handler = new WinHttpHandler(); handler.ServerCertificateValidationCallback = CustomServerCertificateValidationCallback; using (var client = new HttpClient(handler)) { _validationCallbackHistory.ThrowException = true; HttpRequestException ex = await Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync(System.Net.Test.Common.Configuration.Http.SecureRemoteEchoServer)); Assert.True(ex.GetBaseException() is CustomException); } }
public async Task TestWithInValidUrlRaiseException(string baseUrl) { // Arrange httpClient.BaseAddress = new Uri(baseUrl); roadStatusService = new RoadStatusService(loggerMock.Object, httpClient, optionMock.Object); // Act HttpRequestException ex = await Task.Run(() => Assert.ThrowsAsync <HttpRequestException>(async() => await roadStatusService.GetRoadStatusDetail("a2"))); // Assert Assert.AreEqual("Error: Expected Error occured.", ex.Message); Assert.IsTrue(ex.InnerException.Message.Contains("No such host is known")); }
public async Task Should_Throw_FilePath_HttpRequestException() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowInvalidHttpRequestExceptionForFilePath); System.IO.Stream content = default; HttpRequestException exception = await Assert.ThrowsAnyAsync <HttpRequestException>(async() => { content = await BotClient.DownloadFileAsync("Invalid_File_Path"); }); Assert.Contains("404", exception.Message); Assert.Null(content); }
[InlineData("EF", false)] // EF does not work. public async Task IsOfFilterQueryOnTypeDifferentResultUsingDifferentData(string dataSourceMode, bool work) { // Arrange string filter = "?$filter=isof('Microsoft.Test.E2E.AspNet.OData.QueryComposition.IsOf.BillingCustomer')"; var requestUri = string.Format("{0}/{1}/Billings{2}", this.BaseAddress, dataSourceMode, filter); // Act HttpResponseMessage response = null; HttpRequestException exception = null; try { response = await Client.GetAsync(requestUri); } catch (HttpRequestException e) { exception = e; } // Assert if (work) { Assert.True(HttpStatusCode.OK == response.StatusCode); JObject responseString = await response.Content.ReadAsObject <JObject>(); JArray value = responseString["value"] as JArray; Assert.NotNull(value); Assert.Empty(value); Assert.Equal("", string.Join(",", value.Select(e => (int)e["Id"]))); } else { #if NETCORE // AspNetCore does not encounter the error until after the headers have been sent, at which // point is closes the connection. Assert.Null(response); Assert.NotNull(exception); Assert.Contains("Error while copying content to a stream.", exception.Message); #else // AspNet catches the exception and converts it to a 500. Assert.Null(exception); Assert.NotNull(response); Assert.True(HttpStatusCode.InternalServerError == response.StatusCode); Assert.Contains("DbIsOfExpression requires an expression argument with a polymorphic result type that is " + "compatible with the type argument.", await response.Content.ReadAsStringAsync()); #endif } }
public static Mock <HttpMessageHandler> MockRemoteLicenseException(LicenseManagerSingleton mgr, WebExceptionStatus status) { var ex = new HttpRequestException("Mock failure", new WebException("Mock failure", status)); var handler = new Mock <HttpMessageHandler>(); var method = handler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ThrowsAsync(ex); method.Verifiable("SendAsync must be called"); mgr.SetHttpMessageHandler(handler.Object, true); return(handler); }
public async Task <HttpResponseMessage> Send(HttpContext httpContext, string url) { var requestMessage = new HttpRequestMessage(); var requestMethod = httpContext.Request.Method; if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod)) { var streamContent = new StreamContent(httpContext.Request.Body); requestMessage.Content = streamContent; } _httpClient.DefaultRequestHeaders.Clear(); CopyRequestHeaders( httpContext.Request.Headers, requestMessage.Headers, requestMessage.Content?.Headers, new HashSet <string>(StringComparer.OrdinalIgnoreCase) { "host" } // Use HOST header for backend: it might use it for routing ); requestMessage.RequestUri = new Uri(url); requestMessage.Method = new HttpMethod(requestMethod); try { Console.WriteLine("CALLING: " + url); return(await _httpClient.SendAsync( requestMessage, HttpCompletionOption.ResponseHeadersRead, httpContext.RequestAborted)); } catch (HttpRequestException ex) { if (ex.InnerException?.GetType().Name == "CurlException") { var newEx = new HttpRequestException("Error requesting backend URL: " + url, ex); newEx.Data.Add("url", url); throw newEx; } throw; } }
/// <summary> /// Initializes a new instance of the <see cref="BotRequestException"/> class. /// </summary> /// <param name="httpRequestException">The http request exception that is the cause of the current exception.</param> /// <param name="httpResponseMessage">The failed http response.</param> public BotRequestException(HttpRequestException httpRequestException, HttpResponseMessage httpResponseMessage) : base("The response message cannot be read as a valid Bot Response.", httpRequestException) { if (httpRequestException == null) { throw new ArgumentNullException(nameof(httpRequestException)); } if (httpResponseMessage == null) { throw new ArgumentNullException(nameof(httpResponseMessage)); } ErrorCode = (int)httpResponseMessage.StatusCode; Description = httpRequestException.Message; ResponseMessage = httpResponseMessage; }
private static async Task EnsureSuccessTriasResponse(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { var requestString = await GetHttpContentAsStringSave(response.RequestMessage?.Content).ConfigureAwait(false); var responseString = await GetHttpContentAsStringSave(response.Content).ConfigureAwait(false); var ex = new HttpRequestException($"Response status code does not indicate success: {(int)response.StatusCode} ({response.ReasonPhrase}).", null, response.StatusCode); ex.Data["Request"] = requestString; ex.Data["Response"] = responseString; throw ex; } }
public async void IsRunningAsyncWhenResultCodeFails() { var mockLogger = new Mock <ILogger <TrexWebClient> >(); var settings = new TrexWebClient.Settings() { StatusUrl = "http://localhost" }; var socketException = new System.Net.Sockets.SocketException(0); var ex = new HttpRequestException("test", socketException); var httpClient = HttpClientMock.GetResponseThatThrowsException(ex); var webClient = new TrexWebClient(mockLogger.Object, Options.Create(settings), httpClient); (await webClient.IsRunningAsync()).Should().Be(false, "We should swallow the conenction refused exception"); }
public static HttpResponseMessage ProcessGetResponseWebException(HttpRequestException requestException, HttpRequestMessage request, HttpAbortReason abortReason) { var inner = requestException.InnerException; if (inner != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertHttpRequestException(requestException, request, abortReason)); } else { // There is no inner exception so there's not enough information to be able to convert to the correct WCF exception. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(requestException.Message, requestException)); } }
public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException() { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { var e = new DivideByZeroException(); handler.ServerCertificateCustomValidationCallback = delegate { throw e; }; HttpRequestException ex = await Assert.ThrowsAsync <HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); Assert.Same(e, ex.GetBaseException()); } }
public void OrleansSerialization_HttpRequestException_IsEquivalent() { var expected = new HttpRequestException("HTTP request exception").ThrowAndCatch(); var actual1 = (HttpRequestException)_serializationManager.DeepCopy(expected); AssertExceptionsAreEqual(expected, actual1); var actual = _serializationManager.RoundTripSerializationForTesting(expected); var actual2 = _serializationManager.DeserializeFromByteArray <HttpRequestException>(_serializationManager.SerializeToByteArray(expected)); AssertExceptionsAreEqual(expected, actual2); AssertExceptionsAreEqual(expected, actual); }
public async Task CreateRepositoryBranch( string userAgent, string authorizationToken, string repositoryName, string masterBranchName, string newBranchName) { HttpClient httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUri) }; this.SetRequestHeaders(httpClient.DefaultRequestHeaders, userAgent, authorizationToken, null); var requestUri = string.Format(@"repos/{0}/{1}/git/refs", userAgent, repositoryName); var sha = await this.GetSha( userAgent, authorizationToken, repositoryName, masterBranchName).ConfigureAwait(false); var branchRequest = new BranchRequest { Ref = string.Format(@"refs/heads/{0}", newBranchName), Sha = sha, }; HttpResponseMessage response = await httpClient.PostAsJsonAsync(requestUri, branchRequest).ConfigureAwait(false); if (response.IsSuccessStatusCode) { return; } if (Convert.ToInt32(response.StatusCode) == 422) { var error = await response.Content.ReadAsJsonAsync <ErrorResponseDto>().ConfigureAwait(false); if (error.Message == MessagesResponse.ReferenceAlreadyExists) { return; } } var exception = new HttpRequestException(string.Format(@"Response bad satus code: {0}", response.StatusCode)); exception.Data.Add("response", response); throw exception; }
internal override void ParseError(HttpRequestException ex, HttpStatusCode status) { if (status == HttpStatusCode.NotFound) { Result = DeleteContainerResult.NotFound; } else if (status == HttpStatusCode.Conflict) { Result = DeleteContainerResult.NotEmpty; } else { base.ParseError(ex, status); } }
public void SetErrorWithoutResponse(HttpStatusCode code, string message) { var we = new HttpRequestException(); typeof(HttpRequestException).GetField("_message", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(we, message); var request = new Mock <IRequest>(); request.Setup(c => c.GetResponse(It.IsAny <CancellationToken>())).Throws(we); var factory = Mock.Get(RequestFactory); factory.Setup(c => c.Create(It.IsAny <HttpMethod>(), It.IsAny <string>(), It.IsAny <int>())) .Returns(request.Object); }
public void Repository_Returns_Exception_When_WebService_Url_Is_Not_Found() { // Arrange MockHttpMessageHandler mockHttpMessageHandler = new MockHttpMessageHandler(); mockHttpMessageHandler.When(HttpMethod.Get, "/test").Respond(HttpStatusCode.NotFound, "application/json", _webServiceJson); Mock <HttpClient> mockHttpClient = new Mock <HttpClient>(mockHttpMessageHandler); // Act IRepository repository = new WebServiceRepository("http://invalid/test", mockHttpClient.Object); HttpRequestException httpRequestException = Assert.ThrowsAsync <HttpRequestException>(async() => await repository.GetPeopleData()); // Assert Assert.That(httpRequestException.Message, Is.EqualTo("Response status code does not indicate success: 404 (Not Found).")); }
public static HttpResponseMessage EnsureSuccess(this HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { if (response.Content != null) { response.Content.Dispose(); } var ex = new HttpRequestException($"Response status code does not indicate success: {(int)response.StatusCode} ({response.StatusCode})."); ex.Data["StatusCode"] = response.StatusCode; throw ex; } return(response); }
public static void ShowHttpExceptionMessage(HttpRequestException e) { if (e.Message.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) != -1) { ShowMessage($"服务器错误: {e.Message.Replace("Response status code does not indicate success: ", string.Empty)}"); } else if (e.Message == "An error occurred while sending the request.") { ShowMessage("无法连接网络。"); } else { ShowMessage($"请检查网络连接。 {e.Message}"); } }
private async Task HandleServerDown <TResult>(ChoosenNode choosenNode, JsonOperationContext context, RavenCommand <TResult> command, HttpRequestException e) { if (command.FailedNodes == null) { command.FailedNodes = new HashSet <ServerNode>(); } choosenNode.Node.IsFailed = true; command.FailedNodes.Add(choosenNode.Node); var failoverNode = ChooseNodeForRequest(command, e); await ExecuteAsync(failoverNode, context, command); }
/// <summary> /// <para> /// Constructs an exception from a <see cref="HttpRequestException"/> and optional /// request details. /// </para> /// <note> /// This constructor does not initialize the <see cref="StatusCode"/> property for /// .NET Standard 2.x, .NET Core 3.x, and .NET Framework and the <see cref="ReasonPhrase"/> /// is set to the message from <paramref name="requestException"/>. /// </note> /// </summary> /// <param name="requestException">The <see cref="HttpRequestException"/>.</param> /// <param name="requestUri">Optionally specifies the request URL.</param> /// <param name="requestMethod">Optionally specifies the request method.</param> public HttpException(HttpRequestException requestException, string requestUri = null, string requestMethod = null) : base(GetMessage(requestException.Message ?? string.Empty, requestUri, requestMethod), requestException) { Covenant.Requires <ArgumentNullException>(requestException != null, nameof(requestException)); this.RequestUri = requestUri; this.RequestMethod = requestMethod; this.ReasonPhrase = requestException.Message; #if NET5_0_OR_GREATER this.StatusCode = requestException.StatusCode ?? (HttpStatusCode)0; #else this.StatusCode = (HttpStatusCode)0; #endif }
/// <summary> /// Create a new <see cref="KubeClientException"/> with the specified message. /// </summary> /// <param name="message"> /// The exception message. /// </param> /// <param name="innerException"> /// The exception that caused the current exception to be raised. /// </param> public KubeClientException(string message, HttpRequestException <StatusV1> innerException) : base(message, innerException) { if (String.IsNullOrWhiteSpace(message)) { throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'message'.", nameof(message)); } if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } Status = innerException.Response; }
public static Exception ConvertHttpRequestException(HttpRequestException exception, HttpRequestMessage request, HttpAbortReason abortReason) { Contract.Assert(exception.InnerException != null, "InnerException must be set to be able to convert"); uint hresult = (uint)exception.InnerException.HResult; var innerSocketException = exception.InnerException as SocketException; if (innerSocketException != null) { var socketErrorCode = innerSocketException.SocketErrorCode; switch (socketErrorCode) { case SocketError.HostNotFound: return(new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), exception)); default: break; } } if (exception.InnerException is AuthenticationException) { return(new SecurityNegotiationException(SR.Format(SR.TrustFailure, request.RequestUri.Authority), exception)); } switch (hresult) { // .Net Native HttpClientHandler sometimes reports an incorrect handle state when a connection is aborted, so we treat it as a connection reset error case WININET_E_INCORRECT_HANDLE_STATE: goto case WININET_E_CONNECTION_RESET; case WININET_E_CONNECTION_RESET: return(new CommunicationException(SR.Format(SR.HttpReceiveFailure, request.RequestUri), exception)); // Linux HttpClient returns ERROR_INVALID_HANDLE in the endpoint-not-found case, so map to EndpointNotFoundException case UnsafeNativeMethods.ERROR_INVALID_HANDLE: case WININET_E_NAME_NOT_RESOLVED: return(new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), exception)); case CURLE_SSL_CACERT: case CURLE_SSL_CERTPROBLEM: case ERROR_WINHTTP_SECURE_FAILURE: return(new SecurityNegotiationException(SR.Format(SR.TrustFailure, request.RequestUri.Authority), exception)); default: return(new CommunicationException(exception.Message, exception)); } }
[InlineData("EF", false)] // EF does not support complex type inheritance. public async Task IsOfFilterQueryWithComplexTypeProperty(string dataSourceMode, bool work) { // Arrange string filter = "?$filter=isof(Address,'Microsoft.Test.E2E.AspNet.OData.QueryComposition.IsOf.BillingCnAddress')"; var requestUri = string.Format("{0}/{1}/BillingCustomers{2}", this.BaseAddress, dataSourceMode, filter); // Act HttpResponseMessage response = null; HttpRequestException exception = null; try { response = await Client.GetAsync(requestUri); } catch (HttpRequestException e) { exception = e; } // Assert if (work) { Assert.True(HttpStatusCode.OK == response.StatusCode); JObject responseString = await response.Content.ReadAsObject <JObject>(); JArray value = responseString["value"] as JArray; Assert.NotNull(value); Assert.Equal(2, value.Count); Assert.Equal("1,3", string.Join(",", value.Select(e => (int)e["CustomerId"]))); } else { #if NETCORE // AspNetCore does not encounter the error until after the headers have been sent, at which // point is closes the connection. Assert.Null(response); Assert.NotNull(exception); Assert.Contains("Error while copying content to a stream.", exception.Message); #else // AspNet catches the exception and converts it to a 500. Assert.Null(exception); Assert.NotNull(response); Assert.True(HttpStatusCode.InternalServerError == response.StatusCode); #endif } }
public async Task ShouldCatchBadRequest() { Mock <IHttpClientFactory> httpMock = new Mock <IHttpClientFactory>(); var clientHandlerStub = new DelegatingHandlerStub((request, cancellationToken) => { request.SetConfiguration(new HttpConfiguration()); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.BadRequest); return(Task.FromResult(response)); }); Mock <IAuthService> authMock = new Mock <IAuthService>(); var client = new HttpClient(clientHandlerStub); httpMock.Setup(_ => _.CreateClient(It.IsAny <string>())).Returns(client); IPatientService service = new RestPatientService(httpMock.Object, configuration, authMock.Object); HttpRequestException ex = await Assert.ThrowsAsync <HttpRequestException>(() => service.GetPatientPHNAsync("")); }
private static bool CheckError(HttpRequestException x) { if (!x.Data.Contains(nameof(HttpStatusCode))) { return(false); } var statusCode = (HttpStatusCode)x.Data[nameof(HttpStatusCode)]; if (statusCode < HttpStatusCode.InternalServerError) { return(statusCode == HttpStatusCode.RequestTimeout); } return(false); }
public async Task Ensure_SendAsync_Throws_On_Expired_Certificate_On_Linux() { // Arrange var ex = new HttpRequestException(null, new IOException(null, new IOException(null, new IOException(null, new Exception(null, new ExternalException(null, 336151573)))))); var(apns, httpHandlerMock) = BoostrapApnsClient(throwOnResponse: ex); var push = CreateStubPush(); // Act and Assert await Assert.ThrowsAsync <ApnsCertificateExpiredException>(() => apns.SendAsync(push)); }
public void InnerHttpRequestException_RoundTrip_IsStripped() { var webEx = new WebException("Web exception").ThrowAndCatch(); var httpEx = new HttpRequestException("HTTP request exception", webEx).ThrowAndCatch(); var ex = new RemoteServiceException("Remote service exception", "http://foo/bar", httpEx).ThrowAndCatch(); string json = ExceptionSerializer.Serialize(ex); var actual = ExceptionSerializer.Deserialize(json); actual.ShouldBeOfType <RemoteServiceException>(); actual.Message.ShouldBe(ex.Message); actual.StackTrace.ShouldNotBeNullOrEmpty(); actual.InnerException.ShouldBeOfType <WebException>(); actual.InnerException.Message.ShouldBe(webEx.Message); actual.InnerException.StackTrace.ShouldNotBeNullOrEmpty(); }
public static WebDavClientException Create(HttpRequestException x) { var match = Regex.Match(x.Message, @"'(?<code>\d{3})'\s+\('(?<description>.*?)'\)"); if (match.Success) { return(new WebDavClientException( x, (HttpStatusCode)int.Parse(match.Groups["code"].Value), match.Groups["description"].Value)); } else { return(new WebDavClientException(x, null, null)); } }
private ResourceProviderClientException HandleAggregateException(AggregateException aex) { RestClientException <VmBackupErrorResource> restClientException = aex.InnerException as RestClientException <VmBackupErrorResource>; HttpRequestException httpRequestException = aex.InnerException as HttpRequestException; if (httpRequestException != null) { WebException webEx = httpRequestException.InnerException as WebException; if (webEx != null) { return(new ResourceProviderClientException(webEx.Message, webEx) { HttpStatusCode = HttpStatusCode.BadRequest }); } return(new ResourceProviderClientException(httpRequestException.Message, httpRequestException) { HttpStatusCode = HttpStatusCode.BadRequest }); } if (restClientException != null) { VmBackupErrorResource error = restClientException.MessageContent; if (error != null) { return(new ResourceProviderClientException(error.Message) { HttpStatusCode = restClientException.StatusCode, ErrorCode = error.Code, State = error.State, Severity = error.Severity }); } else { return(new ResourceProviderClientException("ServerResources.InternalError") { HttpStatusCode = HttpStatusCode.InternalServerError, ErrorCode = "Constants.UnknownErrorCode" }); } } return(new ResourceProviderClientException(aex.InnerException.Message, aex.InnerException) { HttpStatusCode = HttpStatusCode.InternalServerError }); }
/// <summary> /// Send (or 'ping') the URL of this sites sitemap.xml file to search engines like Google, Bing and Yahoo, /// This method should be called each time the sitemap changes. Google says that 'We recommend that you /// resubmit a Sitemap no more than once per hour.' The way we 'ping' our sitemap to search engines is /// actually an open standard See /// http://www.sitemaps.org/protocol.html#submit_ping /// You can read the sitemap ping documentation for the top search engines below: /// Google - http://googlewebmastercentral.blogspot.co.uk/2014/10/best-practices-for-xml-sitemaps-rssatom.html /// Bing - http://www.bing.com/webmaster/help/how-to-submit-sitemaps-82a15bd4. /// Yahoo - https://developer.yahoo.com/search/siteexplorer/V1/ping.html /// </summary> #if Release public async Task PingSearchEngines() { foreach (string sitemapPingLocation in SitemapPingLocations) { string url = sitemapPingLocation + this.urlHelper.Encode(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetSitemapXml)); HttpResponseMessage response = await this.httpClient.GetAsync(url); if (!response.IsSuccessStatusCode) { HttpRequestException exception = new HttpRequestException(string.Format( CultureInfo.InvariantCulture, "Pinging search engine {0}. Response status code does not indicate success: {1} ({2}).", url, (int)response.StatusCode, response.ReasonPhrase)); this.loggingService.Log(exception); } } }