symfony - 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 之后停止
解决方案
根据文档:
当响应的 HTTP 状态代码在 300-599 范围内(即 3xx、4xx 或 5xx)时,您的代码应该能够处理它。如果你不这样做,getHeaders() 和 getContent() 方法会抛出一个适当的异常
您必须检查$response->getStatusCode()
,或准备处理 a ClientException
(代表 4xx 状态代码)。
推荐阅读
- python - 如何按特定顺序将列添加到数据框中?
- vb.net - 计算 CSV 文件中的唯一值
- jetbrains-ide - Windows 上的 JetBrains IDE:使用 Git Bash 执行运行配置
- python - 当您在调用 show() 之前打开和关闭 PySimpleGui 窗口时,即使图形窗口关闭,Matplotlib 的 show() 函数也会阻塞
- android - 将 lambda 表达式返回类型更改为 Unit
- node.js - 没有任务添加到队列中
- javascript - NextJS 应用暂时显示受限路由组件
- java - Recycler List,CardView 到 Tab 活动中的新片段
- amazon-web-services - 如何使用存储桶名称获取 S3 存储桶的区域?
- javascript - 如何防止 Html.RenderAction 方法在 javascript 中被识别为 html 代码?