-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add unsuccessfull response content logging
- Loading branch information
Showing
2 changed files
with
37 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |