Chidi Nkwocha
Chidi Nkwocha

Reputation: 1

Undefined property: GuzzleHttp\Exception\ConnectException::$status

I keep getting this error when trying to get the status of the request.

This is my code

ExpenseRepository.php

<?php

namespace Expensetrim\Api\v1\Repositories;

use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ExpenseRepository
{
    private $api_url;

    const API_GET = 'GET';
    const API_POST = 'POST';
    const API_PUT = 'PUT';

    function __construct()
    {
        $this->api_url = "http://xxx-xxx-xxx/api/v1/";
    }

    public function api_call($method, $uri, $request = NULL)
{
    try {

        $url=$this->api_url.$uri;
        $client = new Client(['base_uri' => $this->api_url]);
        $response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
    }
    catch (RequestException $e) {
        return $e;
    }
    return $this->formatResponseBody($response);
}

public static function formatResponseBody($response)
{
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

public function addExpenseType($data)
{
    $uri = 'expense/types/add';
    $response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
    return $response;

}

Also CompanyRepository.php

public function addExpenseType($company_id, $data)
    {
        $data['company_id'] = $company_id;
        $expense = new ExpenseRepository;
        $done = $expense->addExpenseType($data);
        if($done->status == 'success') {
          return true;
        }

        return true;
    }

I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status. Please what am i doing wrong?

Upvotes: 0

Views: 2159

Answers (2)

Suraj
Suraj

Reputation: 2277

Change your formatResponseBody function to add $response->getBody()->rewind();

public static function formatResponseBody($response)
{
    $response->getBody()->rewind();
    $body = $response->getBody(true)->getContents();
    return json_decode($body);
}

In the old version of guzzle, it read the full body without resetting the pointer after. Using rewind() will reset the pointer. If this is the source of your issue rewind() will resolve this. It has aleady been resolved in newer versions.

Upvotes: 1

Hamoud
Hamoud

Reputation: 1929

There is an exception thrown at this line:

catch (RequestException $e) {
    return $e;
}

and you are returning the exception. The return value of the method addExpenseType is actually an exception thrown by Guzzle.

throw the exception to see the error. change your code to

catch (RequestException $e) {
        throw $e;
    }

Upvotes: 1

Related Questions