首页 > 解决方案 > 如果出现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 循环

标签: phplaravellaravel-5foreach

解决方案


尝试使用全局异常类,它将捕获所有类型的错误,

    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;
            }

        }
    }
}

推荐阅读