我正在围绕 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,这应该是默认设置,但它也不起作用。
尝试改变
$handlerStack = new HandlerStack(new CurlHandler());
到
$handlerStack = HandlerStack::create(new CurlHandler());
这对我有用。
狂饮处理者
了解 Guzzle 使用的几个请求选项需要特定的中间件包装客户端使用的处理程序,这一点很重要。您可以通过将处理程序包装在 GuzzleHttp\HandlerStack::create(callable $handler = null) 静态方法中来确保提供给客户端的处理程序使用默认中间件。
您可以尝试以下代码:
$handler = new CurlHandler();
$stack = HandlerStack::create($handler);