2016-11-14 52 views
0

我正在向URL請求以使用Goutte獲取數據。但是我提出請求的服務器很慢。所以有時候laravel會拋出超時錯誤。當出現這個錯誤時,我必須在數據庫中輸入這個錯誤日誌以及一些額外的數據(即id等)。我在互聯網上搜索。但我發現所有與自定義錯誤消息等相關的解決方案。我想要的是,當laravel拋出超時錯誤時,我必須在數據庫中輸入其他數據,然後重定向頁面。如果有人知道解決方案,將不勝感激。數據庫中的Laravel錯誤報告

這是我的代碼。

use Goutte\Client; 
class WebScrapingController extends Controller { 
    public function index() { 
     try { 
      $this->crawler = $this->client->request('GET', $url . '?' . $data); 
     }catch(Exception $e){ 
      // Here I want to make entry in database and then redirect to another page 
      dd(['Connection time out', $i, $e]); 
     } 
    } 
} 

這是我的錯誤信息

ConnectException in CurlFactory.php line 186: 
cURL error 7: Failed to connect to myurl port 80: Connection timed out (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) 

還收到此錯誤有時

RequestException in CurlFactory.php line 187: 
cURL error 56: Recv failure: Connection timed out (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) 

我使用laravel 5.3和this刮刀。

回答

1

嗯,這是我會怎麼做:

use Goutte\Client; 
class WebScrapingController extends Controller { 
    public function index() { 
     try { 
      $this->crawler = $this->client->request('GET', $url . '?' . $data); 
     } catch(\ConnectException $e){ 
      $log = new Log();//define this as a model 
      $log->setMessage($e->getMessage()); 
      $log->save(); 
     } catch(\RequestException $e){ 
      $log = new Log();//define this as a model 
      $log->setMessage($e->getMessage()); 
      $log->save(); 
     } finally { 
      $yourModel = YourNamespace\YourModel::find($url);//or, depends on your model structure and DB 
      $yourModel = YourNamespace\YourModel::where('url',$url)->first(); 
     } 
    } 
} 

您還可以將日誌的saving在一個私有方法,我把它這樣,所以你可以看到,它是可以治療幾個例外不同,或者你可以趕上作爲一般例外:

public function index() { 
     try { 
      $this->crawler = $this->client->request('GET', $url . '?' . $data); 
     } catch(\Exception $e){ 
      $log = new Log();//define this as a model 
      $log->setMessage($e->getMessage()); 
      $log->save(); 
     } finally { 
      $yourModel = YourNamespace\YourModel::find($url);//or, depends on your model structure and DB 
      $yourModel = YourNamespace\YourModel::where('url',$url)->first(); 
     } 
    } 

如果你想登錄你有Log門面一些文件:use Illuminate\Support\Facades\Log;

+0

答案是我所期望的。所以我很容易理解。但我終於無法理解使用了。你能解釋一下嗎? –

+1

無論如何,最後都會執行,因此即使在記錄異常之後,您仍然可以查詢數據庫並檢索和輸出數據(請參閱:http://php.net/manual/en/language.exceptions.php) –