我想存储一些产品型号。我正在使用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循环
答案 0 :(得分:2)
尝试使用全局异常类,它将捕获所有类型的错误,
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;
}
}
}
}