2

i am learning web api in c#. i want to know how to catch exception message from the response object send from the server side.

suppose this is the response exception message being thrown by the server side. so how do i catch it on the client side. by using normal try catch its not showing the message.

try
{
}
catch{Exception exception)
{

var errorMessage = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(exception.Message) };
                    throw new HttpResponseException(errorMessage);
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
himu_74
  • 49
  • 2
  • 6
  • Check this question, you might get some clues. http://stackoverflow.com/questions/12260300/throwing-httpresponseexception-in-webapi-action-method-returning-empty-200-respo – Vinod Mar 29 '14 at 07:15

2 Answers2

3

It depends on who is a client of Web API.

  • C# client "exception" style - you will not receive a direct exception thrown. You should examine returned HttpResponseMessage by yourself.

    using (var client = new HttpClient() { BaseAddress = "http://someurl.com" } )
    using (var responseMessage = await client.GetAsync("resources/123")
    {
        try
        {
            // EnsureSuccessStatusCode will throw HttpRequestException exception if 
            // status code is not successfull
            responseMessage.EnsureSuccessStatusCode();
    
            // Here you should process your response if it is successfull.
            // Something like
            // var result = await responseMessage.Content.ReadAsAsync<MyClass>();
        }
        catch (HttpRequestException)
        {
            var errorContent = await responseMessage.Content.ReadAsStringAsync();
            // "errorContent" variable will contain your exception message.
        } 
    }
    
  • C# client "if" style - also you can achieve the same result without raising exception

    if (responseMessage.IsSuccessStatusCode)
    {
        // Here you should process your response if it is successfull.
        // Something like
        // var result = await responseMessage.Content.ReadAsAsync<MyClass>();
    }
    else
    {
        var errorContent = await responseMessage.Content.ReadAsStringAsync();
        // "errorContent" variable will contain your exception message.
    }
    
  • JavaScript - depends on what library you will use for calling service, but usually all of them provide some error callback parameter where you can pass your error handling function.

  • 2
    Adding to your answer, you can not use await in catch block. The next C# version will support. – PSR Mar 10 '15 at 07:35
0

I just want to add the whole process of sending exception from server side to client side :

1- On server side :

[HttpGet]
public HttpResponseMessage DoSomething([FromUri] string ValtoProcess)
{
    try
    {
       return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new { result, message });
    }
    catch(exception ex)
    {
       HttpResponseMessage Response =Request.CreateErrorResponse(HttpStatusCode.InternalServerError,ex.InnerException.Message);
            throw new HttpResponseException(Response);
     }

and then on client side just in case of response status is not ok read the error as follows :

string ErrorMessage = await TaskReponse.Content.ReadAsStringAsync();
Hany Hassan
  • 320
  • 2
  • 10