【问题标题】:Guzzle not throwing exceptionsGuzzle 不抛出异常
【发布时间】:2021-11-21 04:40:10
【问题描述】:

我正在围绕 themoviedb.org api 构建一个类包装器。我在请求中使用 guzzle 7,但它似乎没有抛出任何异常。

namespace App\Classes;

use App\Models\Movie;
use App\Models\Series;
use GuzzleHttp\Client;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Uri;

use Psr\Http\Message\RequestInterface;

class TMDBScraper{

private string $apiKey;
private string $language;
private Client $client;
private const API_URL = "http://api.themoviedb.org/3/";
private const IMAGE_URL = "http://image.tmdb.org/t/p/";
private const POSTER_PATH_SIZE = "w500";
private const BACKDROP_PATH_SIZE = "original";


public function __construct(string $apiKey = "default_api_key") {
    $this->apiKey = $apiKey;
    $this->language = app()->getLocale();

    $handlerStack = new HandlerStack(new CurlHandler());
    $handlerStack->unshift(Middleware::mapRequest(function (RequestInterface $request) {
        return $request->withUri(Uri::withQueryValues($request->getUri(), [
            'api_key' => $this->apiKey,
            'language' => $this->language
        ]));
    }));

    $this->client = new Client([
        'base_uri' => self::API_URL,
        'handler' => $handlerStack
    ]);

}

public function search($screenplayType, $query): ?array {

    try {

        $response = json_decode($this->client->get('search/' . $screenplayType, [
            'query' => compact('query')
        ])->getBody());

        return $this->toModel($response, $screenplayType);

    } catch (GuzzleException $e) {
        echo $e->getMessage();
        return null;
    }

}

... more code }

我尝试使用错误的 api 密钥,但没有抛出客户端异常。我也尝试将http_errors设置为true,应该默认设置,但也没有用。

【问题讨论】:

  • 一开始没有GuzzleException类,改成here看
  • @bhucho 你的意思是没有导入 GuzzleException 类?我为导入添加了更多代码,因为它是导入的。正如guzzle docs 中所述,GuzzleException 还处理 ClientException
  • 不能调用 GuzzleException 是接口不是类,由 TransferException 实现,见异常树docs.guzzlephp.org/en/latest/quickstart.html#exceptions

标签: php laravel exception request guzzle


【解决方案1】:

你可以试试这个代码:

$handler = new CurlHandler();
$stack = HandlerStack::create($handler);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2012-01-24
    • 2013-05-24
    • 2010-12-09
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多