public async Task RequestWithException_ShouldWrapWithUnhandledException() { _testinghost.Instance.When(a => a.DoSomething()).Throw(x => new ArgumentException("MyEx")); var request = await GetRequestFor<IDemoService>(p => p.DoSomething()); var responseJson = await (await new HttpClient().SendAsync(request)).Content.ReadAsStringAsync(); var responseException = _exceptionSerializer.Deserialize(responseJson); responseException.ShouldBeOfType<UnhandledException>(); }
public async Task RequestWithException_ShouldNotWrap(Type exceptionType) { _testinghost.Instance.When(a => a.DoSomething()).Throw(i => (Exception)Activator.CreateInstance(exceptionType, "MyEx", null, null, null)); var request = await GetRequestFor <IDemoService>(p => p.DoSomething()); var responseJson = await(await new HttpClient().SendAsync(request)).Content.ReadAsStringAsync(); var responseException = JsonExceptionSerializer.Deserialize(responseJson); responseException.ShouldBeOfType(exceptionType); }
public void RequestException_RoundTrip_IsIdentical() { var expected = new RequestException("message").ThrowAndCatch(); var json = JsonExceptionSerializer.Serialize(expected); var actual = JsonExceptionSerializer.Deserialize(json); actual.ShouldBeOfType <RequestException>(); actual.Message.ShouldBe(expected.Message); actual.StackTrace.ShouldBe(expected.StackTrace); }
public void HttpRequestException_RoundTrip_ReturnsSubstitue() { var ex = new HttpRequestException("message").ThrowAndCatch(); var json = JsonExceptionSerializer.Serialize(ex); var actual = JsonExceptionSerializer.Deserialize(json); var envException = actual.ShouldBeOfType <EnvironmentException>(); envException.RawMessage().ShouldEndWith(ex.RawMessage()); envException.UnencryptedTags["originalStackTrace"].ShouldBe(ex.StackTrace); }
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 = JsonExceptionSerializer.Serialize(ex); var actual = JsonExceptionSerializer.Deserialize(json); actual.ShouldBeOfType <RemoteServiceException>(); actual.Message.ShouldBe(ex.Message); actual.StackTrace.ShouldBe(ex.StackTrace); actual.InnerException.ShouldBeOfType <WebException>(); actual.InnerException.Message.ShouldBe(webEx.Message); actual.InnerException.StackTrace.ShouldBe(webEx.StackTrace); }
public void ExceptionTypeNotAvailable_RoundTrip_FallsBackToAvailableType() { var expected = new MyException(30000, "message") { MyNumber = 42 }.ThrowAndCatch(); var json = JsonExceptionSerializer.Serialize(expected); json = json.Replace("MyException", "MyNonexistentException"); var actual = (RequestException)JsonExceptionSerializer.Deserialize(json); actual.ShouldBeOfType <RequestException>(); actual.Message.ShouldBe(expected.Message); actual.ErrorCode.ShouldBe(30000); actual.ExtendedProperties.Count.ShouldBe(1); actual.ExtendedProperties.Single().ShouldBe(new KeyValuePair <string, object>("MyNumber", 42L)); actual.StackTrace.ShouldBe(expected.StackTrace); }
private async Task <object> InvokeCore(HttpServiceRequest request, Type resultReturnType, JsonSerializerSettings jsonSettings) { if (request == null) { throw new ArgumentNullException(nameof(request)); } request.Overrides = TracingContext.TryGetOverrides(); request.TracingData = new TracingData { HostName = CurrentApplicationInfo.HostName?.ToUpperInvariant(), ServiceName = CurrentApplicationInfo.Name, RequestID = TracingContext.TryGetRequestID(), SpanID = Guid.NewGuid().ToString("N"), //Each call is new span ParentSpanID = TracingContext.TryGetSpanID() }; PrepareRequest?.Invoke(request); var requestContent = _serializationTime.Time(() => JsonConvert.SerializeObject(request, jsonSettings)); var serviceEvent = EventPublisher.CreateEvent(); serviceEvent.TargetService = ServiceName; serviceEvent.TargetMethod = request.Target.MethodName; serviceEvent.RequestId = request.TracingData?.RequestID; serviceEvent.SpanId = request.TracingData?.SpanID; serviceEvent.ParentSpanId = request.TracingData?.ParentSpanID; var config = GetConfig(); while (true) { string responseContent; HttpResponseMessage response; IEndPointHandle endPoint = await ServiceDiscovery.GetNextHost(serviceEvent.RequestId).ConfigureAwait(false); // The URL is only for a nice experience in Fiddler, it's never parsed/used for anything. var uri = string.Format(BuildUri(endPoint, config) + ServiceName); if (request.Target.MethodName != null) { uri += $".{request.Target.MethodName}"; } if (request.Target.Endpoint != null) { uri += $"/{request.Target.Endpoint}"; } try { Log.Debug(_ => _("ServiceProxy: Calling remote service. See tags for details.", unencryptedTags: new { remoteEndpoint = endPoint.HostName, remotePort = endPoint.Port ?? DefaultPort, remoteServiceName = ServiceName, remoteMethodName = request.Target.MethodName })); serviceEvent.TargetHostName = endPoint.HostName; var httpContent = new StringContent(requestContent, Encoding.UTF8, "application/json"); httpContent.Headers.Add(GigyaHttpHeaders.Version, HttpServiceRequest.Version); serviceEvent.RequestStartTimestamp = Stopwatch.GetTimestamp(); try { response = await GetHttpClient(config).PostAsync(uri, httpContent).ConfigureAwait(false); responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } finally { serviceEvent.ResponseEndTimestamp = Stopwatch.GetTimestamp(); } IEnumerable <string> values; if (response.Headers.TryGetValues(GigyaHttpHeaders.ExecutionTime, out values)) { var time = values.FirstOrDefault(); TimeSpan executionTime; if (TimeSpan.TryParse(time, out executionTime)) { serviceEvent.ServerTimeMs = executionTime.TotalMilliseconds; } } } catch (HttpRequestException ex) { Log.Error("The remote service failed to return a valid HTTP response. Continuing to next " + "host. See tags for URL and exception for details.", exception: ex, unencryptedTags: new { uri }); endPoint.ReportFailure(ex); _hostFailureCounter.Increment("RequestFailure"); serviceEvent.Exception = ex; EventPublisher.TryPublish(serviceEvent); // fire and forget! continue; } catch (TaskCanceledException ex) { _failureCounter.Increment("RequestTimeout"); Exception rex = new RemoteServiceException("The request to the remote service exceeded the " + "allotted timeout. See the 'RequestUri' property on this exception for the URL that was " + "called and the tag 'requestTimeout' for the configured timeout.", uri, ex, unencrypted: new Tags { { "requestTimeout", LastHttpClient?.Timeout.ToString() }, { "requestUri", uri } }); serviceEvent.Exception = rex; EventPublisher.TryPublish(serviceEvent); // fire and forget! throw rex; } if (response.Headers.Contains(GigyaHttpHeaders.ServerHostname) || response.Headers.Contains(GigyaHttpHeaders.Version)) { try { endPoint.ReportSuccess(); if (response.IsSuccessStatusCode) { var returnObj = _deserializationTime.Time(() => JsonConvert.DeserializeObject(responseContent, resultReturnType, jsonSettings)); serviceEvent.ErrCode = 0; EventPublisher.TryPublish(serviceEvent); // fire and forget! _successCounter.Increment(); return(returnObj); } else { Exception remoteException; try { remoteException = _deserializationTime.Time(() => JsonExceptionSerializer.Deserialize(responseContent)); } catch (Exception ex) { _applicationExceptionCounter.Increment("ExceptionDeserializationFailure"); throw new RemoteServiceException("The remote service returned a failure response " + "that failed to deserialize. See the 'RequestUri' property on this exception " + "for the URL that was called, the inner exception for the exact error and the " + "'responseContent' encrypted tag for the original response content.", uri, ex, unencrypted: new Tags { { "requestUri", uri } }, encrypted: new Tags { { "responseContent", responseContent } }); } _applicationExceptionCounter.Increment(); serviceEvent.Exception = remoteException; EventPublisher.TryPublish(serviceEvent); // fire and forget! if (remoteException is RequestException || remoteException is EnvironmentException) { ExceptionDispatchInfo.Capture(remoteException).Throw(); } if (remoteException is UnhandledException) { remoteException = remoteException.InnerException; } throw new RemoteServiceException("The remote service returned a failure response. See " + "the 'RequestUri' property on this exception for the URL that was called, and the " + "inner exception for details.", uri, remoteException, unencrypted: new Tags { { "requestUri", uri } }); } } catch (JsonException ex) { _failureCounter.Increment("Serialization"); Log.Error(_ => _("The remote service returned a response with JSON that failed " + "deserialization. See the 'uri' tag for the URL that was called, the exception for the " + "exact error and the 'responseContent' encrypted tag for the original response content.", exception: ex, unencryptedTags: new { uri }, encryptedTags: new { responseContent })); serviceEvent.Exception = ex; EventPublisher.TryPublish(serviceEvent); // fire and forget! throw new RemoteServiceException("The remote service returned a response with JSON that " + "failed deserialization. See the 'RequestUri' property on this exception for the URL " + "that was called, the inner exception for the exact error and the 'responseContent' " + "encrypted tag for the original response content.", uri, ex, new Tags { { "responseContent", responseContent } }, new Tags { { "requestUri", uri } }); } } else { var exception = response.StatusCode == HttpStatusCode.ServiceUnavailable ? new Exception($"The remote service is unavailable (503) and is not recognized as a Gigya host at uri: {uri}"): new Exception($"The remote service returned a response but is not recognized as a Gigya host at uri: {uri}"); endPoint.ReportFailure(exception); _hostFailureCounter.Increment("NotGigyaHost"); if (response.StatusCode == HttpStatusCode.ServiceUnavailable) { Log.Error(_ => _("The remote service is unavailable (503) and is not recognized as a Gigya host. Continuing to next host.", unencryptedTags: new { uri })); } else { Log.Error(_ => _("The remote service returned a response but is not recognized as a Gigya host. Continuing to next host.", unencryptedTags: new { uri, statusCode = response.StatusCode }, encryptedTags: new { responseContent })); } serviceEvent.ErrCode = 500001; //(int)GSErrors.General_Server_Error; EventPublisher.TryPublish(serviceEvent); // fire and forget! } } }