Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why detailed error message is not passed to HttpClient?

I am using the default Web Api controller that is auto generated. I am testing the validation and error handling in the client side. But somehow I have realised that the detail error message is not passed to client. Either if I throw HttpResponseException or returning IHttpActionResult in both cases the client is seeing only "Bad Request" but not the detailed message. Can anyone explain what is going wrong please?

     public IHttpActionResult Delete(int id)
    {
        if (id <= 0)
        {
            var response = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent("Id should be greater than zero.", System.Text.Encoding.UTF8, "text/plain"),
                StatusCode = HttpStatusCode.NotFound

            };
            throw new HttpResponseException(response) // Either this way
        }

        var itemToDelete = (from i in Values
                            where i.Id == id
                            select i).SingleOrDefault();

        if (itemToDelete == null)
        {
            return BadRequest(string.Format("Unable to find a value for the Id {0}", id)); // Or This way
        }

        Values.Remove(itemToDelete);
        return Ok();
    }

client code is as:

 private async static Task DeleteValue(int id)
    {

        var url = "http://localhost:13628/api/Values/" + id;
        using (var client = new HttpClient())
        {
            var response = await client.DeleteAsync(url);
            if (response.IsSuccessStatusCode)
            {
                await ReadValues();
            }
            else
            {
                Console.WriteLine(response.ReasonPhrase);
                Console.WriteLine(response.StatusCode);
            }
        }
    }

None of the above works??

Thx

like image 378
user1829319 Avatar asked Oct 24 '16 10:10

user1829319


1 Answers

In your client side change Console.WriteLine(response.ReasonPhrase);

to Console.WriteLine(response.Content.ReadAsStringAsync().Result);

and it will give the detailed error message.

like image 160
Buddhi Madarasinghe Avatar answered Nov 09 '22 13:11

Buddhi Madarasinghe