diff --git a/src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs b/src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs index 3259dce0c..403aa2b2b 100644 --- a/src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs +++ b/src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs @@ -48,7 +48,8 @@ public static async Task 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) diff --git a/src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs b/src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs new file mode 100644 index 000000000..c5adb4ca5 --- /dev/null +++ b/src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs @@ -0,0 +1,35 @@ +namespace Digdir.Domain.Dialogporten.Infrastructure; + +public static class HttpResponseMessageExtensions +{ + private const int MaxContentLength = 1000; + + public static async Task 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; +}