Skip to content

Communications.HttpPostAsync() swallows httpClient exceptions without logging #60

@vbodo

Description

@vbodo
mannequin

The _client.PostAsync() call is wrapped in a try/catch block. If the HttpClient throws an exception, the exception is caught and the method returns null without logging anything. This makes it very difficult to identify and troubleshoot communication issues such as timeouts.

        /// <summary>
        /// Sends a POST request with the given XML to the API, asynchronously
        /// Prefer the use of this method over HttpPost
        /// </summary>
        /// <param name="xmlRequest">The XML to send to the API</param>
        /// <param name="cancellationToken"></param>
        /// <returns>The XML response on success, null otherwise</returns>
        public async Task<string> HttpPostAsync(string xmlRequest, CancellationToken cancellationToken)
        {
            // First, read values from the config that we need that relate to logging
            _config.TryGetValue("logFile", out var logFile);
            var printXml = _config.ContainsKey("printxml") && "true".Equals(_config["printxml"]);

            // Log any data to the appropriate places, only if we need to
            if (printXml)
            {
                Console.WriteLine(xmlRequest);
                Console.WriteLine(logFile);
            }
            if (logFile != null)
            {
                Log(xmlRequest, logFile);
            }
            
            // Now that we have gotten the values for logging from the config, we need to actually send the request
            try
            {
                OnHttpAction(RequestType.Request, xmlRequest);
                var xmlContent = new StringContent(xmlRequest, Encoding.UTF8, "application/xml");
                var response = await _client.PostAsync(_config["url"], xmlContent, cancellationToken);
                var xmlResponse = await response.Content.ReadAsStringAsync();
                OnHttpAction(RequestType.Response, xmlResponse);

                if (printXml)
                {
                    Console.WriteLine(xmlResponse);
                }
                if (logFile != null)
                {
                    Log(xmlResponse, logFile);
                }

                return xmlResponse;
            }
            catch (Exception)
            {
                return null;
            }
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions