HttpClient does not report an exception returned from the web API

I am using HttpClient to call my MVC 4 web api. In my Web API call, it returns a domain object. If something goes wrong, an HttpResponseException with a configured message will be thrown on the server.

  [System.Web.Http.HttpGet] public Person Person(string loginName) { Person person = _profileRepository.GetPersonByEmail(loginName); if (person == null) throw new HttpResponseException( Request.CreateResponse(HttpStatusCode.NotFound, "Person not found by this id: " + id.ToString())); return person; } 

I see a customized error message in the response body using IE F12. However, when I call it using HttpClient , I do not receive a customized error message, but only an http code. "ReasonPhrase" is always "not found" for 404 or "Internal server error" for 500 codes.

Any ideas? How to send back a custom error message from the web API, and keep the normal return type as an object of my domain?

+6
source share
3 answers

(Put my answer here for better formatting)

Yes, I saw this, but HttpResponseMessage does not have a body property. I realized this myself: response.Content.ReadAsStringAsync().Result; . Code example:

 public T GetService<T>( string requestUri) { HttpResponseMessage response = _client.GetAsync(requestUri).Result; if( response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<T>().Result; } else { string msg = response.Content.ReadAsStringAsync().Result; throw new Exception(msg); } } 
+14
source

I used some logic when catching an exception from the answer.

This makes it easy to catch an exception, an internal exception, an internal exception :), etc.

 public static class HttpResponseMessageExtension { public static async Task<ExceptionResponse> ExceptionResponse(this HttpResponseMessage httpResponseMessage) { string responseContent = await httpResponseMessage.Content.ReadAsStringAsync(); ExceptionResponse exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(responseContent); return exceptionResponse; } } public class ExceptionResponse { public string Message { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } public string StackTrace { get; set; } public ExceptionResponse InnerException { get; set; } } 

For a full discussion, see this blog post .

+1
source

The custom error message will be in the "body" of the response.

0
source

Source: https://habr.com/ru/post/923626/


All Articles