Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnexpectedHttpStatusCodeException: more verbose message #333

Merged
merged 4 commits into from
May 28, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Pliner marked this conversation as resolved.
Show resolved Hide resolved
{
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();
}
}
Loading