How to catch REST API bad request message

newbie2018newbie2018 Member ✭✭
edited May 16 in Xamarin.Forms

I tried to send some error messages from my web api to Xamarin Form app when some exceptions happen. But if response.IsSuccessStatusCode is false, the response.Content is null and can't catch those error messages. The code of Xamarin Form app

                    HttpResponseMessage response = await httpClient.PostAsync(uri, content);
                    if (response.IsSuccessStatusCode)
                    {
                        var returnObject = await response.Content.ReadAsStringAsync();
                        string strResponse = JsonConvert.DeserializeObject<string>(returnObject);
                    }
                    else
                    {
                        var returnObject = await response.Content.ReadAsStringAsync();
                    }

And web api send error message like this

    try
    {
        //don something...
        return this.Request.CreateResponse(HttpStatusCode.OK, "successful");
    }
    catch(Exception ex)
    {
        return this.Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
    }

Any way to catch ex.Message in Xamarin Form app when the exception happens?

Posts

Sign In or Register to comment.