Accessing Raw Body with Exception with Http Utils

Version 6.4.1

The docs located here show how to retrieve the body from the request with an exception but it seems that it is always null.

The code is

  var json = await url.PostJsonToUrlAsync(employee, requestFilter: (r) => r.AddBearerToken(_apiKey));
catch (Exception ex)
  var knownError = ex.IsBadRequest()
  || ex.IsNotFound()
  || ex.IsUnauthorized()
  || ex.IsForbidden()
  || ex.IsInternalServerError();

  var isAnyClientError = ex.IsAny400();
  var isAnyServerError = ex.IsAny500();

  HttpStatusCode? errorStatus = ex.GetStatus();
  string errorBody = ex.GetResponseBody();
  // errorBody is always null even though the server is returning JSON

I confirmed this request with the server in postman is returning:

That only works when using .NET HttpWebRequest, it’s not possible to read the response body from a HttpClient HttpRequestException.

What is your recommendation?

You’d need to use the HttpClient directly and call GetAsync to check for an error status response instead of calling EnsureSuccessStatusCode() which throws the Exception.

1 Like