首页 > 解决方案 > Symfony 忽略获取请求的 404 状态码

问题描述

我有一个允许用户创建愿望的应用程序。我使用每个希望的标题来发出 api 请求以取消启动以下载图片。我现在有一个问题,用户可以输入一个不从 unsplash 返回任何图像的标题。在这种情况下,我想使用占位符图像,但我的代码在收到 404 错误后停止。有没有办法忽略这个错误并继续我的循环?

 public function fetchImagesFromUnsplash() {

    $wishes = $this->repository->findAll();
    foreach ($wishes as $wish) {
            try {
                $response = $this->httpClient->request('GET', 'https://api.unsplash.com/photos/random', [
                    'query' => [
                        'query' => $wish->getDescription(),
                        'client_id' => 'oa1DsGebE8ehCV9SrvcA1mCx-2QfvnufUKgsIY5N0Mk'
                    ]
                ]);

            } catch (TransportExceptionInterface $e) {
            }

            if ($response) {
                $data = $response->getContent();
                $data = json_decode($data, true);
                $imageLink = $data['urls']['raw'];
                $rawImage = file_get_contents($imageLink);

                if ($rawImage) {
                    file_put_contents("public/images/" . sprintf('imageWish%d.jpg', $wish->getId()), $rawImage);
                    $wish->setImagePath(sprintf('public/images/imageWish%d.jpg', $wish->getId()));
                } else {
                $wish->setImagePath('placeholder.png');
                }
                $this->em->flush();
            }
        }
    }

编辑:

我试过这个:

  public function fetchImagesFromUnsplash() {

    $wishes = $this->repository->findAll();
    foreach ($wishes as $wish) {
            try {
                $response = $this->httpClient->request('GET', 'https://api.unsplash.com/photos/random', [
                    'query' => [
                        'query' => $wish->getDescription(),
                        'client_id' => 'oa1DsGebE8ehCV9SrvcA1mCx-2QfvnufUKgsIY5N0Mk'
                    ]
                ]);

            } catch (NotFoundHttpException $e) {
            }

            if ($response) {
                $data = $response->getContent();
                $data = json_decode($data, true);
                $imageLink = $data['urls']['raw'];
                $rawImage = file_get_contents($imageLink);

                if ($rawImage) {
                    file_put_contents("public/images/" . sprintf('imageWish%d.jpg', $wish->getId()), $rawImage);
                    $wish->setImagePath(sprintf('public/images/imageWish%d.jpg', $wish->getId()));
                } else {
                    $wish->setImagePath('placeholder.png');
                }

            }  
        }
    $this->em->flush();

}

但它仍然在第一个 404 之后停止

标签: symfonyhttpgetrequesthttp-status-code-404

解决方案


根据文档

当响应的 HTTP 状态代码在 300-599 范围内(即 3xx、4xx 或 5xx)时,您的代码应该能够处理它。如果你不这样做,getHeaders() 和 getContent() 方法会抛出一个适当的异常

您必须检查$response->getStatusCode(),或准备处理 a ClientException(代表 4xx 状态代码)。


推荐阅读