How to catch an error occurred on a webapi server?

2

I have a server running a WebAPI service, on the client I run the call to a POST URL like this:

try
{
   HttpWebRequest request;

   request = (HttpWebRequest)WebRequest.Create(URL);

   request.Method = "POST";
   request.Proxy = null;
   request.ContentType = "application/json";

   byte[] dataStream = Encoding.UTF8.GetBytes(DATA);
   Stream newStream = request.GetRequestStream();
   newStream.Write(dataStream, 0, dataStream.Length);
   newStream.Close();

   request.GetResponse();
}
catch (Exception ex)
{

   //QUERO LER O ERRO AQUI
}

On the server I'll do the following:

try
{

...

}
catch (Exception ex)
{

   return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex);
}

The problem is that in the client it comes a exception saying that it took error 500, I know that exception does not "come" from the server, which is generated in the client, but I would like to know how I get the inner all generated in CreateErrorResponse

    
asked by anonymous 21.05.2015 / 00:09

1 answer

2

By default, the details of the exception that occurred on the server are not placed in the HTTP response. This is to not show details of the server's implementation to the client - it is a security measure. The less the client knows about the server guts, the better.

The exception details are only placed in the HTTP response if the client is local, that is, if the client and server were on the same computer.

However, if this API is for internal consumption, you can choose to display the exception details for all clients, using HttpConfiguration.IncludeErrorDetailPolicy .

In the WebApiConfig.cs file, add:

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

On the server, the exception will be converted to an instance of HttpError " and serialized in the response body. So, on the client side, just convert back to HttpError .

Note: It is preferable to use HttpClient instead of WebRequest to make HTTP requests because it has a high-level API and avoids dealing directly with byte streams. This whole code can be written like this:

using (var client = new HttpClient())
{
    var response = await client.PostAsJsonAsync("url", data);

    if (response.IsSuccessStatusCode)
    {
        var error = await response.Content.ReadAsAsync<HttpError>();
    }
    else
    {
        var responseData = await response.Content.ReadAsAsync<Model>();
    }
}
    
21.05.2015 / 00:46