我在尝试获取请求状态时一直收到此错误。
这是我的代码
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;
}
还有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;
}
我需要检查状态是否成功,但不断收到此错误:未定义的属性:GuzzleHttp \ Exception \ ConnectException :: $ status。 请问我做错了什么?
答案 0 :(得分:0)
此行引发异常:
catch (RequestException $e) {
return $e;
}
并且您将返回异常。方法addExpenseType
的返回值实际上是Guzzle抛出的异常。
抛出异常以查看错误。 将您的代码更改为
catch (RequestException $e) {
throw $e;
}
答案 1 :(得分:0)
更改formatResponseBody
功能以添加$response->getBody()->rewind();
public static function formatResponseBody($response)
{
$response->getBody()->rewind();
$body = $response->getBody(true)->getContents();
return json_decode($body);
}
在guzzle
的旧版本中,它会在不重置指针之后读取完整的正文。使用rewind()
将重置指针。如果这是您的问题的根源,rewind()
将解决此问题。它已在新版本中得到解决。