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
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'
– Ricardo
@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.– dcastro
I can’t find this class
HttpError
in no DLL, you can show me how I captured the errorHttpWebRequest
?– Ricardo
@user3517631 tries to import nuget
Microsoft.AspNet.WebApi.Core
– dcastro
I had already tried, did not appear, in vdd he broke the reference of my Newtonsoft.Json
– Ricardo
@user3517631 This nuget has to work. Look here: https://dotnetfiddle.net/ScY79s
– dcastro
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.– dcastro