private void ParseErrorInformationThrowException(
            IRestResponse restResponse)
        {
            this.loggerWrapper.Warning(
                $"A non-successful status code was returned " +
                $"({restResponse.StatusCode}).");

            // Deserialise the data as the standard error model.
            string content = restResponse.Content;

            this.loggerWrapper.Debug($"content = \"{content}\"");
            this.loggerWrapper.Debug(
                $"Attempting to de-serialise the body (\"{content}\") " +
                $"as a {nameof(HttpErrorBody)} instance...");

            HttpErrorBody httpErrorBody = null;

            try
            {
                httpErrorBody =
                    JsonConvert.DeserializeObject <HttpErrorBody>(content);

                this.loggerWrapper.Warning(
                    $"{nameof(httpErrorBody)} = {httpErrorBody}");
            }
            catch (JsonReaderException jsonReaderException)
            {
                this.loggerWrapper.Warning(
                    $"Could not de-serialise error body to an instance " +
                    $"of {nameof(HttpErrorBody)}.",
                    jsonReaderException);
            }

            throw new TranslationApiAdapterException(httpErrorBody);
        }
示例#2
0
 /// <summary>
 /// Initialises a new instance of the
 /// <see cref="SpiWebServiceException" /> class.
 /// </summary>
 /// <param name="httpStatusCode">
 /// The actual <see cref="HttpStatusCode" /> resulting in the exception
 /// being thrown.
 /// </param>
 /// <param name="httpErrorBody">
 /// An instance of type <see cref="HttpErrorBody" />.
 /// </param>
 public SpiWebServiceException(
     HttpStatusCode httpStatusCode,
     HttpErrorBody httpErrorBody)
     : base(BuildExceptionMessage(httpStatusCode))
 {
     this.HttpStatusCode = httpStatusCode;
     this.HttpErrorBody  = httpErrorBody;
 }
示例#3
0
        private static HttpErrorBody CreateHttpErrorBody(
            HttpStatusCode httpStatusCode,
            string errorIdentifier,
            string message)
        {
            HttpErrorBody toReturn = new HttpErrorBody()
            {
                StatusCode      = httpStatusCode,
                ErrorIdentifier = errorIdentifier,
                Message         = message,
            };

            return(toReturn);
        }
示例#4
0
        /// <summary>
        /// Inspects a particular <see cref="IActionResult" /> instance,
        /// and if it's an error, logs it out.
        /// </summary>
        /// <param name="actionResult">
        /// An instance of type <see cref="IActionResult" />.
        /// </param>
        protected void LogOutgoingErrors(IActionResult actionResult)
        {
            // Is it an error?
            JsonResult jsonResult = actionResult as JsonResult;

            if (jsonResult != null && jsonResult.Value is HttpErrorBody)
            {
                HttpErrorBody httpErrorBody =
                    jsonResult.Value as HttpErrorBody;

                this.loggerWrapper.Warning(
                    $"This request ended with a (handled) error being " +
                    $"returned: {httpErrorBody}.");
            }
        }
        private static string BuildExceptionMessage(
            HttpErrorBody httpErrorBody)
        {
            string toReturn = null;

            string statusCode = httpErrorBody == null
                ?
                                "Status Code Unavailable!"
                :
                                httpErrorBody.StatusCode.ToString();

            toReturn = string.Format(
                CultureInfo.InvariantCulture,
                Message,
                statusCode,
                nameof(HttpErrorBody));

            return(toReturn);
        }
        protected async Task <DataAdapterResult <T>[]> GetEntitiesFromApi <T>(
            string[] identifiers,
            Dictionary <string, AggregateQuery> aggregateQueries,
            string[] fields,
            bool live,
            DateTime?pointInTime,
            CancellationToken cancellationToken)
        {
            var bearerToken = _executionContextManager.SpiExecutionContext.IdentityToken;
            var entityType  = GetPluralUrlEntityName <T>();

            if (string.IsNullOrEmpty(entityType))
            {
                throw new Exception($"Unsupported entity type {typeof(T)}");
            }

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseUrl, UriKind.Absolute);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
                client.DefaultRequestHeaders.Add(SpiHeaderNames.InternalRequestIdHeaderName,
                                                 _executionContextManager.SpiExecutionContext.InternalRequestId.ToString());
                if (!string.IsNullOrEmpty(_executionContextManager.SpiExecutionContext.ExternalRequestId))
                {
                    client.DefaultRequestHeaders.Add(SpiHeaderNames.ExternalRequestIdHeaderName,
                                                     _executionContextManager.SpiExecutionContext.ExternalRequestId);
                }

                var body = JsonConvert.SerializeObject(
                    new SpiAdapterBatchRequest
                {
                    Identifiers      = identifiers,
                    AggregateQueries = aggregateQueries,
                    Fields           = fields,
                    Live             = live,
                    PointInTime      = pointInTime,
                }, SerializerSettings);
                _logger.Debug($"Calling {SourceName} adapter at {_baseUrl} with {body}");
                var response = await client.PostAsync(
                    entityType,
                    new StringContent(body, Encoding.UTF8, "application/json"),
                    cancellationToken);

                if (!response.IsSuccessStatusCode)
                {
                    HttpErrorBody errorBody = null;
                    try
                    {
                        var errorJson = await response.Content.ReadAsStringAsync();

                        errorBody = JsonConvert.DeserializeObject <HttpErrorBody>(errorJson);
                    }
                    catch (Exception ex)
                    {
                        var fullUrl = new Uri(new Uri(_baseUrl, UriKind.Absolute), new Uri(entityType, UriKind.Relative));
                        _logger.Warning($"Error reading standard error response from {(int)response.StatusCode} response from {fullUrl}: {ex.Message}");
                    }

                    throw new DataAdapterException($"Error calling {SourceName} adapter")
                          {
                              AdapterName         = SourceName,
                              RequestedEntityName = entityType,
                              RequestedIds        = identifiers,
                              RequestedFields     = fields,
                              HttpStatusCode      = response.StatusCode,
                              HttpErrorBody       = errorBody,
                          };
                }

                var json = await response.Content.ReadAsStringAsync();

                var entities = JsonConvert.DeserializeObject <T[]>(json);

                var results = new DataAdapterResult <T> [identifiers.Length];
                for (var i = 0; i < identifiers.Length; i++)
                {
                    results[i] = new DataAdapterResult <T>
                    {
                        Identifier = identifiers[i],
                        Entity     = entities[i],
                    };
                }

                return(results);
            }
        }
示例#7
0
 /// <summary>
 /// Initialises a new instance of the
 /// <see cref="HttpErrorBodyResult" /> class.
 /// </summary>
 /// <param name="errorBody">
 /// Error details
 /// model.
 /// </param>
 public HttpErrorBodyResult(
     HttpErrorBody errorBody)
     : base(errorBody, errorBody.StatusCode)
 {
 }
 /// <summary>
 /// Initialises a new instance of the
 /// <see cref="TranslationApiAdapterException" /> class.
 /// </summary>
 /// <param name="httpErrorBody">
 /// An instance of <see cref="Common.Models.HttpErrorBody" />.
 /// </param>
 public TranslationApiAdapterException(HttpErrorBody httpErrorBody)
     : base(BuildExceptionMessage(httpErrorBody))
 {
     this.HttpErrorBody = httpErrorBody;
 }