/// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class. /// </summary> /// <param name="errorCode">HTTP status code.</param> /// <param name="message">Error message.</param> /// <param name="errorContent">Error content.</param> /// <param name="headers">HTTP Headers.</param> /// <param name="clientErrorResponse">Detailed client error response.</param> public ApiException(int errorCode, string message, object errorContent = null, Multimap <string, string> headers = null, ClientErrorResponse clientErrorResponse = null) : base(message) { this.ErrorCode = errorCode; this.ErrorContent = errorContent; this.Headers = headers; this.clientErrorResponse = clientErrorResponse; }
public void OnResponse(HttpResponse httpResponse) { TransportResponse transportResponse = new TransportResponse(httpResponse); if (transportResponse.hasError()) { ClientErrorResponse clientErrorResponse = transportResponse.getError(); callback.OnError(clientErrorResponse); } else { TResponse response = responseDecoder.DecodeResponse(transportResponse); callback.OnSuccess(response); } }
public void GetGreeting_Async_ServerError() { RestClient client = new RestClient(urlPrefix); GetRequestBuilder <int, Greeting> requestBuilder = new GetRequestBuilder <int, Greeting>("/basicCollection"); requestBuilder.SetID(-1); GetRequest <int, Greeting> request = requestBuilder.Build(); AutoResetEvent blocker = new AutoResetEvent(false); Greeting greeting = null; ClientErrorResponse errorResponse = null; RestliCallback <EntityResponse <Greeting> > .SuccessHandler successHandler = delegate(EntityResponse <Greeting> response) { greeting = response.element; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > .ErrorHandler errorHandler = delegate(ClientErrorResponse response) { errorResponse = response; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > callback = new RestliCallback <EntityResponse <Greeting> >(successHandler, errorHandler); client.RestRequestAsync(request, callback); blocker.WaitOne(); Assert.IsNull(greeting); Assert.IsNotNull(errorResponse); Assert.AreEqual(400, errorResponse.status); RestliException error = errorResponse.error; Assert.IsNotNull(error); Assert.IsNotNull(error.Message); Assert.IsNull(error.InnerException); ErrorResponse details = error.details; Assert.IsNotNull(details); Assert.AreEqual(400, details.status); Assert.AreEqual("Negative key.", details.message); Assert.AreEqual("com.linkedin.restli.server.RestLiServiceException", details.exceptionClass); Assert.IsTrue(details.hasStackTrace); }
public void CreateGreeting_Async() { RestClient client = new RestClient(urlPrefix); GreetingBuilder greetingBuilder = new GreetingBuilder(); greetingBuilder.id = 0; // Dummy value greetingBuilder.message = "Create me!"; greetingBuilder.tone = new Tone(Tone.Symbol.FRIENDLY); Greeting input = greetingBuilder.Build(); CreateRequestBuilder <int, Greeting> requestBuilder = new CreateRequestBuilder <int, Greeting>("/basicCollection"); requestBuilder.input = input; CreateRequest <int, Greeting> request = requestBuilder.Build(); AutoResetEvent blocker = new AutoResetEvent(false); CreateResponse <int, Greeting> createResponse = null; ClientErrorResponse errorResponse = null; RestliCallback <CreateResponse <int, Greeting> > .SuccessHandler successHandler = delegate(CreateResponse <int, Greeting> response) { createResponse = response; blocker.Set(); }; RestliCallback <CreateResponse <int, Greeting> > .ErrorHandler errorHandler = delegate(ClientErrorResponse response) { errorResponse = response; blocker.Set(); }; RestliCallback <CreateResponse <int, Greeting> > callback = new RestliCallback <CreateResponse <int, Greeting> >(successHandler, errorHandler); client.RestRequestAsync(request, callback); blocker.WaitOne(asyncTimeoutMillis); Assert.IsNull(errorResponse); Assert.AreEqual(RestConstants.httpStatusCreated, createResponse.status); Assert.AreEqual(123, createResponse.key); CollectionAssert.AreEqual(new List <string>() { "/basicCollection/123" }, createResponse.headers[RestConstants.kHeaderLocation].ToList()); }
public void FinderGreeting_Async() { RestClient client = new RestClient(urlPrefix); FinderRequestBuilder <Greeting, EmptyRecord> requestBuilder = new FinderRequestBuilder <Greeting, EmptyRecord>("/basicCollection"); requestBuilder.Name("search"); requestBuilder.SetParam("tone", Tone.Symbol.FRIENDLY); FinderRequest <Greeting, EmptyRecord> request = requestBuilder.Build(); AutoResetEvent blocker = new AutoResetEvent(false); CollectionResponse <Greeting, EmptyRecord> collectionResponse = null; ClientErrorResponse errorResponse = null; RestliCallback <CollectionResponse <Greeting, EmptyRecord> > .SuccessHandler successHandler = delegate(CollectionResponse <Greeting, EmptyRecord> response) { collectionResponse = response; blocker.Set(); }; RestliCallback <CollectionResponse <Greeting, EmptyRecord> > .ErrorHandler errorHandler = delegate(ClientErrorResponse response) { errorResponse = response; blocker.Set(); }; RestliCallback <CollectionResponse <Greeting, EmptyRecord> > callback = new RestliCallback <CollectionResponse <Greeting, EmptyRecord> >(successHandler, errorHandler); client.RestRequestAsync(request, callback); blocker.WaitOne(asyncTimeoutMillis); Assert.IsNull(errorResponse); IReadOnlyList <Greeting> greetings = collectionResponse.elements; Assert.IsTrue(greetings.Count() > 0); Assert.IsTrue(greetings.All(_ => _.message.Equals("search") && _.tone.symbol == Tone.Symbol.FRIENDLY)); Assert.AreEqual(10, collectionResponse.paging.count); Assert.AreEqual(0, collectionResponse.paging.start); CollectionAssert.AllItemsAreInstancesOfType(collectionResponse.paging.links.ToList(), typeof(Link)); Assert.AreEqual("application/json", collectionResponse.paging.links[0].type); }
public void GetGreeting_Async_HttpError() { RestClient client = new RestClient(badUrlPrefix); GetRequestBuilder <int, Greeting> requestBuilder = new GetRequestBuilder <int, Greeting>("/basicCollection"); requestBuilder.SetID(123); GetRequest <int, Greeting> request = requestBuilder.Build(); AutoResetEvent blocker = new AutoResetEvent(false); Greeting greeting = null; ClientErrorResponse errorResponse = null; RestliCallback <EntityResponse <Greeting> > .SuccessHandler successHandler = delegate(EntityResponse <Greeting> response) { greeting = response.element; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > .ErrorHandler errorHandler = delegate(ClientErrorResponse response) { errorResponse = response; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > callback = new RestliCallback <EntityResponse <Greeting> >(successHandler, errorHandler); client.RestRequestAsync(request, callback); blocker.WaitOne(); Assert.IsNull(greeting); Assert.IsNotNull(errorResponse); Assert.AreEqual(500, errorResponse.status); Assert.IsNotNull(errorResponse.error); Assert.IsNull(errorResponse.error.details); Assert.IsNotNull(errorResponse.error.Message); Assert.IsNotNull(errorResponse.error.InnerException); }
public void GetGreeting_Async() { RestClient client = new RestClient(urlPrefix); GetRequestBuilder <int, Greeting> requestBuilder = new GetRequestBuilder <int, Greeting>("/basicCollection"); requestBuilder.SetID(123); GetRequest <int, Greeting> request = requestBuilder.Build(); AutoResetEvent blocker = new AutoResetEvent(false); Greeting greeting = null; ClientErrorResponse errorResponse = null; RestliCallback <EntityResponse <Greeting> > .SuccessHandler successHandler = delegate(EntityResponse <Greeting> response) { greeting = response.element; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > .ErrorHandler errorHandler = delegate(ClientErrorResponse response) { errorResponse = response; blocker.Set(); }; RestliCallback <EntityResponse <Greeting> > callback = new RestliCallback <EntityResponse <Greeting> >(successHandler, errorHandler); client.RestRequestAsync(request, callback); blocker.WaitOne(asyncTimeoutMillis); Assert.IsNull(errorResponse); Assert.IsNotNull(greeting); Assert.AreEqual(123, greeting.id); Assert.AreEqual(Tone.Symbol.SINCERE, greeting.tone.symbol); Assert.AreEqual("Hello World!", greeting.message); }
public void DecodeResponse() { ErrorResponseDecoder decoder = new ErrorResponseDecoder(); Dictionary <string, object> data = new Dictionary <string, object>() { { "exceptionClass", "com.linkedin.restli.server.RestLiServiceException" }, { "message", "Example message" }, { "stackTrace", "Example stack trace" }, { "status", 400 } }; Dictionary <string, string> headers = new Dictionary <string, string>() { { RestConstants.kHeaderRestliErrorResponse, "true" } }; RestliException exception = new RestliException("Server returned Rest.li error response", null); HttpResponse httpResponse = new HttpResponse(RestConstants.httpStatusInternalServerError, headers, null, exception); TransportResponse transportResponse = new TransportResponse(data, httpResponse); ClientErrorResponse response = decoder.DecodeResponse(transportResponse); ErrorResponse error = response.error.details; Assert.IsNotNull(error); Assert.IsTrue(error.hasExceptionClass); Assert.IsTrue(error.hasMessage); Assert.IsTrue(error.hasStackTrace); Assert.IsTrue(error.hasStatus); Assert.AreEqual("com.linkedin.restli.server.RestLiServiceException", error.exceptionClass); Assert.AreEqual("Example message", error.message); Assert.AreEqual("Example stack trace", error.stackTrace); Assert.AreEqual(400, error.status); }
private async Task <ApiResponse <T> > ExecAsync <T>(RestRequest req, IReadableConfiguration configuration, Dictionary <int, Type> returnTypes = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse <T> response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = await client.ExecuteAsync <T>(req, cancellationToken).ConfigureAwait(false); } var status = (int)response.StatusCode; if (returnTypes.ContainsKey(status)) { var type = returnTypes[status]; var JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration); if (!response.IsSuccessful) { var clientErrorResponse = (ClientErrorResponse)JsonSerializer.Deserialize(response, type); String reason = ""; if (clientErrorResponse != null && clientErrorResponse.Errors.Any() && !string.IsNullOrWhiteSpace(clientErrorResponse.Errors.FirstOrDefault().Detail)) { List <Error> errors = clientErrorResponse.Errors; reason = errors.FirstOrDefault().Detail; for (int i = 1; i < errors.Count; i++) { if (string.IsNullOrWhiteSpace(errors[i].Detail)) { reason = reason + " ||| " + errors[i].Detail; } } } if (clientErrorResponse == null && response.Headers != null) { Error error = new Error(); foreach (var header in response.Headers) { if (string.Equals(header.Name, "x-factset-api-request-key", StringComparison.CurrentCultureIgnoreCase)) { error.Id = header.Value.ToString(); } } clientErrorResponse = new ClientErrorResponse() { Errors = new List <Error>() { error } }; } Multimap <string, string> responseHeaders = new Multimap <string, string>(); foreach (var header in response.Headers) { responseHeaders.Add(header.Name, header.Value.ToString()); } throw new ApiException(status, "error", reason, responseHeaders, clientErrorResponse); } if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } else { response.Data = (T)JsonSerializer.Deserialize(response, type); } } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) { result.Cookies = new List <Cookie>(); } foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return(result); }
public void OnError(ClientErrorResponse response) { errorHandler(response); }