Skip to content

Commit

Permalink
UnexpectedHttpStatusCodeException: more verbose message
Browse files Browse the repository at this point in the history
  • Loading branch information
Ilya Nikulshin committed May 28, 2024
1 parent 109778f commit 5759ba0
Showing 1 changed file with 40 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net;
using System.Runtime.Serialization;
using System.Text;

namespace EasyNetQ.Management.Client;

Expand All @@ -13,23 +14,15 @@ public class UnexpectedHttpStatusCodeException : Exception
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//

private const string NoRequest = "<null>";

public HttpStatusCode StatusCode { get; private init; }
public int StatusCodeNumber => (int)StatusCode;

public UnexpectedHttpStatusCodeException()
{
}

public UnexpectedHttpStatusCodeException(HttpStatusCode statusCode) :
base($"Unexpected Status Code: {(int)statusCode} {statusCode}")
{
StatusCode = statusCode;
}

public UnexpectedHttpStatusCodeException(HttpResponseMessage response) :
base($"Unexpected Status Code: {(int)response.StatusCode} {response.StatusCode} from request: {response.RequestMessage?.ToString() ?? NoRequest}")
base(BuildMessage(response))
{
StatusCode = response.StatusCode;
}
Expand All @@ -48,4 +41,42 @@ StreamingContext context
) : base(info, context)
{
}

private static string BuildMessage(HttpResponseMessage response)
{
var sb = new StringBuilder("Unexpected response: StatusCode: ");
sb.Append((int)response.StatusCode);
sb.Append(" ");
sb.Append(response.StatusCode);
sb.Append(", Content: ");
if (response.Content != null)
{
try
{
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
sb.Append('\'');
sb.Append(content);
sb.Append('\'');
}
catch
{
sb.Append("<not a string>");
}
}
else
{
sb.Append("<null>");
}
sb.Append(" from request: ");
if (response.RequestMessage != null)
{
sb.Append(response.RequestMessage);
}
else
{
sb.Append("<null>");
}

return sb.ToString();
}
}

0 comments on commit 5759ba0

Please sign in to comment.