0

I have a firebase data base and I do (CRUD) operation on it, so .. How can i check if there's a response or if there's data before Get it ? I retrive data but not check it .. How can I do it in try and catch ? Helper Class :

 public class Helper
    {
        public static async Task<TEntity> Get<TEntity>(string url)
        {
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

            HttpClient client = new HttpClient(clientHandler);

            var response = await client.GetAsync(url);
            var json = await response.Content.ReadAsStringAsync();
            
            return JsonConvert.DeserializeObject<TEntity>(json);
        }
    }

And this ViewModel class :

public class PatientListPageModelView : BaseViewModel
    {
        private ObservableCollection<Patient> _Patient = new ObservableCollection<Patient>();

        public ObservableCollection<Patient> Patients { get => _Patient; set => SetProperty(ref _Patient, value, nameof(Patients)); }

        

        private ICommand _Appearing;
        private Patient _SelectedPatient;

        public ICommand Appearing { get => _Appearing; set => SetProperty(ref _Appearing, value, nameof(Appearing)); }


        public PatientListPageModelView()
        {

            Appearing = new AsyncCommand(async () => await LoadData());
        }

        async Task LoadData()
        {
            Patients = new ObservableCollection<Patient>((List<Patient>)await PatientService.GetUserPatients());

        }

        public Patient SelectedPatient
        {
            get => _SelectedPatient;
            set
            {
                if (value != null)
                {
                    App.Current.MainPage = new NavigationPage(new Views.TopBarProfile(value));
                }
                _SelectedPatient = value;
                OnPropertyChanged();
            }
        }
    }

So, where i can put check or handle this error ?

Edit : this is my Service to get the data :

public static async Task<IEnumerable<Patient>> GetUserPatients()
        {
            var url = await firebaseClient
                     .Child($"Specalists/406707265/Patients").BuildUrlAsync();

            var result = await Helper.Get<List<Patient>>(url);
            return result ;
        }
renad sahal
  • 147
  • 10
  • I don't see any code that uses `Get`. Add it to question. (That is, add the code that does the firebase operation, which eventually results in use of `Get`.) Then, can't you just wrap the calling code in `try .. catch`? For example, if somewhere you have `await firebase...;` consider doing `try { await firebase....; } catch { ... }`? – ToolmakerSteve Apr 17 '22 at 18:50
  • is this related to https://stackoverflow.com/questions/71897245/newtonsoft-json-jsonserializationexception-message-cannot-deserialize-the-curren? Why are you posting another question under a different user rather than responding to the original question? – Jason Apr 17 '22 at 19:03
  • @ToolmakerSteve I did u can check it – renad sahal Apr 17 '22 at 19:11
  • Ok. If you want to `try ... catch ...` somewhere, and it is `var result = await Helper.Get>(url);` that might fail, then isn't the answer "wrap that line in a try-catch"??? More precisely: `try { var result = await Helper.Get>(url); return result; } catch { ...your-exception-handling-code...; return ...; }` – ToolmakerSteve Apr 17 '22 at 19:33
  • @ToolmakerSteve I don't want to catch any Exception, I want to check if response = 200 not exactly in try and catch but any thing can do the job is accepted, also what is the best way to handle that no data received ? – renad sahal Apr 17 '22 at 19:42
  • just check the response code, or use EnsureSuccessStatusCode. – Jason Apr 17 '22 at 19:50
  • @ToolmakerSteve can u explain EnsureSuccessStatusCode more ? – renad sahal Apr 17 '22 at 19:52
  • https://stackoverflow.com/questions/21097730/usage-of-ensuresuccessstatuscode-and-handling-of-httprequestexception-it-throws – Jason Apr 17 '22 at 19:54

1 Answers1

1

to check the HTTP response code

HttpClient client = new HttpClient(clientHandler);

var response = await client.GetAsync(url);

if (response.StatusCode == HttpStatusCode.OK)
{
  // 200
} 
Jason
  • 86,222
  • 15
  • 131
  • 146
  • I should put it helper class correct ? – renad sahal Apr 17 '22 at 22:05
  • that is the only place where you are using HttpClient – Jason Apr 17 '22 at 22:07
  • and else what should contains ? – renad sahal Apr 17 '22 at 22:09
  • I have error `Helper.Get(string)': not all code paths return a value ` – renad sahal Apr 17 '22 at 22:10
  • 1
    I am not the one writing your app. What do the requirements say should happen if it receives a non-200 response? How do you want it to behave? That is not a question we can answer for you. The error you are getting is a basic C# error - see https://stackoverflow.com/questions/21197410/c-sharp-compiler-error-not-all-code-paths-return-a-value – Jason Apr 17 '22 at 22:14