php - 如果出现QueryException,如何继续循环?
问题描述
我想存储一些产品模型。我用 curl 获取这些数据,有时会发生意外错误。但是当这种情况发生时,我想继续 foreach 循环。我怎样才能做到这一点 ?
private function storeAllModels()
{
foreach ($this->models as $model_bundle) {
foreach ($model_bundle as $model) {
$source = $this->getSourceWithCurl($this->base_url . "/" . $model);
$details = $this->getModelDetails($source);
if ($details == "error") {
array_push($this->errors, $model);
continue;
}
try {
$model = new Product();
$model::forceCreate($details);
} catch (QueryException $e) {
array_push($this->errors, $model);
continue;
}
}
}
}
我使用 try catch 语句,但仍然有错误打破 foreach 循环
解决方案
尝试使用全局异常类,它将捕获所有类型的错误,
private function storeAllModels()
{
foreach ($this->models as $model_bundle) {
foreach ($model_bundle as $model) {
$source = $this->getSourceWithCurl($this->base_url . "/" . $model);
$details = $this->getModelDetails($source);
if ($details == "error") {
array_push($this->errors, $model);
continue;
}
try {
$model = new Product();
$model::forceCreate($details);
} catch (\Exception $e) {
array_push($this->errors, $model);
continue;
}
}
}
}
推荐阅读
- node.js - 读取和写入 json 文件,但它不起作用
- javascript - JS/Mongoose:根据另一个值的排序位置更新数组元素
- javascript - Vue - 无法在处理程序方法中访问组件功能/数据
- scala - 将 ZIO Stream 的输出写入文件
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'/tmp/cats-v-dog
- reactjs - 让 VSCode 自动完成 React 道具类型和名称?
- r - 用于分组数据和 R 中带有日期的两个变量的 facet ggplot
- c# - 从不完全重复的对象列表中删除多余(重复)对象
- c++ - 如何在 C++ 中异步存储和弹出 uint8_t 从/到 uint32_t?
- java - 无法查看 JSP 文件中的数据