How to capture an error occurring on a webapi server?

Asked

Viewed 780 times

2

I have a server where runs a Webapi service, in the client I run the call to a POST URL so:

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 do the treatment like this:

try
{

...

}
catch (Exception ex)
{

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

The problem is that in the customer he comes a exception saying that made mistake 500, I know that the exception not "coming" from the server, which is generated in the client, but I would like to know how I get the inner all generated in the CreateErrorResponse

1 answer

2


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

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

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

In the file WebApiConfig.cs, adds:

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

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

Note: it is preferable to use the HttpClient instead of WebRequest to make HTTP requests, as 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>();
    }
}
  • I sub the suggested change for the servers, but I don’t understand where I see the execption message, I keep capturing in the cach, but I can’t find anything in it. Can you give me an example of where to find this? It can be with 'Webrequest' or 'Httpclient'

  • @user3517631 I’ve updated the answer, where I show how to read the body of the HTTP response and convert to an instance of HttpError. This object contains the details of the exception.

  • I can’t find this class HttpError in no DLL, you can show me how I captured the error HttpWebRequest?

  • @user3517631 tries to import nuget Microsoft.AspNet.WebApi.Core

  • I had already tried, did not appear, in vdd he broke the reference of my Newtonsoft.Json

  • @user3517631 This nuget has to work. Look here: https://dotnetfiddle.net/ScY79s

  • If you only need the message, you can also convert the reply to a Jobject and extract the message like this: (await response.Content.ReadAsAsync<JObject>()).Value<string>("ExceptionMessage"). I haven’t tried it but I think it works.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.