Search code examples
restweb-serviceshttpxamarin.formshttpclient

How to organize HTTP Responses in a Service in Xamarin.Forms app


I'm working on Xamarin.Forms App. One of my example request is:

        public async Task<CheckedUser> CheckUserAccount(User user)
        {
            try
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    clientMoeZdravje.DefaultRequestHeaders.Clear();
                    clientMoeZdravje.DefaultRequestHeaders.Add("Accept", "application/json");
                    var postData = JsonConvert.SerializeObject(user);
                    var response = await clientMoeZdravje.PostAsync($"api/User/CheckUser", new StringContent(postData, Encoding.UTF8, "application/json"));
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonMessage;
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                        {
                            jsonMessage = new StreamReader(responseStream).ReadToEnd();
                        }
                        CheckedUser responseData = (CheckedUser)JsonConvert.DeserializeObject(jsonMessage, typeof(CheckedUser));
                        return responseData;
                    }
                    else
                    {

                        return null;
                    }
                }
                else
                {

                    return null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                string error = ex.Message;
                return null;
            }
        }

As u can see if StatusCode is 200 i return the User object or return null, but the null means no internet connect and bad request also. I don't know how to organize every response i get. For example if StatusCode is 400/500/404 etc. to return string message , or if don't have internet connect return message for NoInternet , also for Exceptions return messages. What is the best practice to organize this?


Solution

  • You can return the CheckedUser with a property responseStatusCode instead of return null.

    In your CheckedUser, add a new property let's say it responseStatusCode. Then you does not need to return null and you can return a new CheckedUser with responseStatusCode. After that you can check responseStatusCode every time you get response.