500 error from failed Remote::get

Hi,

I am using a little get request in my Kirby build to query an api to get some data. This is the snippet:

<?php

$request = Remote::get('https://public.ecologi.com/users/mikeharrisondesign/impact');

if(!empty($request)):

if ($request->code() === 200):
  $results = $request->json();
  $trees = $results['trees'];
  $carbon = $results['carbonOffset'];

?>

<div class="mt-2 text-xs italic opacity-70">
  <?= $trees ?> trees planted so far with 
  <a 
  class="py-[3px] inline-block focus:outline-none focus:outline-offset-4 focus:outline-dashed focus:outline-[#2A353F] underline hover:text-[#cc6324] transition duration-200"
  target="_blank" 
  rel="noopener noreferrer" 
  href="https://ecologi.com/mikeharrisondesign?r=5d88d24c78a2d7000f930584">Ecologi</a>, 
  offsetting about <?= $carbon ?> tonnes of carbon.
</div>

<?php
endif;
endif;
?>

However, I am getting intermittent 500 errors, I think when this api call fails. I thought my if statements would guard against this but they don’t seem to be. Do I need to change the structure of this somehow?

Any help very much appreciated!

That check doesn’t make sense because the request returns a request object (or throws an error).

Try to wrap your command in a try/catch to catch and handle any errors

Hi,
Thanks for the reply, that has done the trick
Mike