2016-11-14 55 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) –