dimanche 31 juillet 2022

Guzzle Laravel simple connection and errors checker

Im using Guzzle on a laravel Project, I want to have a working validation for Api connection and error checker, Also want to keep a sequence while checking, for example, first check the connection if its 200 if isnt then show the Connection error message. If is 200 then proceed to second check that checking if has errors from the remote server like "duplicate ID" then show the error message. If has no error then make the POST or GET request is it possible that? because now when i run this im getting error regarding variable $errormsg error:

 Trying to get property 'error' of non-object

And thats happened because if hasn't errors on server response the field strval(simplexml_load_string($response)->response->errors->error->message) doesnt exist on xml , so is it possible to check if that field is empty or not without getting error?

My function:

  public function showinvoice()
    {
        $client = new \GuzzleHttp\Client([
            'http_errors' => false,
            'headers' => [
                'aade-user-id' => 'blabla',
                'Ocp-Apim-Subscription-Key' => 'blablabla',
               
            ]
        ]);

        $request = $client->GET('https://mydatapi.aade.gr/myDATA/RequestMyExpenses/?dateFrom=11/11/2021&dateTo=11/12/2022');

        $response = $request->getBody()->getContents();

        $reasonPhrase = $request->getReasonPhrase();

        $statusCode = $request->getStatusCode();
        $errormsg = strval(simplexml_load_string($response)->response->errors->error->message);
        if ($statusCode <= 200) { 

            if (isset($errormsg)) {

                $this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $errormsg]);
            }
            else{
               return $response;
            }
   
        } 
        else {
            $this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $statusCode .' '. $reasonPhrase]);
        }
    }
    ```


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire