Skip to content

Commit

Permalink
Add unsuccessfull response content logging
Browse files Browse the repository at this point in the history
  • Loading branch information
elsand committed Oct 21, 2024
1 parent 71698bf commit 623a0c0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public static async Task<HttpResponseMessage> PostAsJsonEnsuredAsync(
configureHeaders?.Invoke(httpRequestMessage.Headers);
configureContentHeaders?.Invoke(httpRequestMessage.Content.Headers);
var response = await client.SendAsync(httpRequestMessage, cancellationToken);
response.EnsureSuccessStatusCode();
await response.EnsureSuccessStatusCodeWithContent();

return response;
}
catch (Exception e)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace Digdir.Domain.Dialogporten.Infrastructure;

public static class HttpResponseMessageExtensions
{
private const int MaxContentLength = 1000;

public static async Task<HttpResponseMessage> EnsureSuccessStatusCodeWithContent(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return response;
}

var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}

if (content.Length > MaxContentLength)
{
content = content[..MaxContentLength] + "[truncated after " + MaxContentLength + " characters]";
}

throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() +
" with error content: " + content, null, response.StatusCode);

}

private static string GetResponseCodeWithReasonPhrase(this HttpResponseMessage response) =>
string.IsNullOrWhiteSpace(response.ReasonPhrase)
? response.StatusCode.ToString()
: response.StatusCode + " " + response.ReasonPhrase;
}

0 comments on commit 623a0c0

Please sign in to comment.