简体   繁体   中英

Catching cURL errors with PHP/Laravel

For my Laravel application, I use the Goutte package to crawl DOMs, which allows me to use guzzle settings.

$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
    'timeout' => 15,
));
$goutteClient->setClient($guzzleClient);

$crawler = $goutteClient->request('GET', 'https://www.google.com/');

I'm currently using guzzle's timeout feature, which will return an error like this, for example, when the client times out:

cURL error 28: Operation timed out after 1009 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html )

Now this is cool and all, but I don't actually want it to return a cURL error and stop my program.

I'd prefer something like this:

if (guzzle client timed out) {
    do this
} else {
    do that
}

How can I do this?

Use the inbuilt Laravel Exception class.

Solution:

<?php

namespace App\Http\Controllers;

use Exception;

class MyController extends Controller
{
    public function index()
    {
        try
        {
            $crawler = $goutteClient->request('GET', 'https://www.google.com');
        }
        catch(Exception $e)
        {
            logger()->error('Goutte client error ' . $e->getMessage());
        }
    }
}

Figured it out. Guzzle has its own error handling for requests.

Source: http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

Solution:

use GuzzleHttp\Exception\RequestException;

...

try {
    $crawler = $goutteClient->request('GET', 'https://www.google.com');
    $crawlerError = false;
} catch (RequestException $e) {
    $crawlerError = true;
}


if ($crawlerError == true) {
    do the thing
} else {
   do the other thing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM