Example: fetch errors
A fixture server that answers every path differently: a page, a redirect, a 404, a 500, a page that takes three seconds, a redirect loop and a page that echoes the User-Agent. run.php requests each one with a 1 second timeout and at most 3 redirects and shows how the failure arrives.
The fixture server
php
<?php
declare(strict_types=1);
// A small fake website for the examples: every path answers in a different way.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
switch ($path) {
case '/ok':
echo '<title>It works</title><meta property="og:site_name" content="Fixture site">';
break;
case '/missing':
http_response_code(404);
echo '<title>Page not found | Fixture site</title><meta name="robots" content="noindex">';
break;
case '/error':
http_response_code(500);
echo '<title>Internal Server Error</title>';
break;
case '/slow':
// answers after 3 seconds, longer than the timeout of the client
sleep(3);
echo '<title>Too late</title>';
break;
case '/moved':
header('Location: /ok', true, 301);
break;
case '/loop':
// redirects to itself forever
header('Location: /loop', true, 302);
break;
case '/echo-user-agent':
echo '<title>' . htmlspecialchars($_SERVER['HTTP_USER_AGENT'] ?? '') . '</title>';
break;
default:
http_response_code(404);
}
return true;The code
php
<?php
declare(strict_types=1);
// Every way parseUrl() can fail, against a fixture server (site/router.php):
// HTTP errors, a timeout, too many redirects and a refused connection.
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use Tomaj\Scraper\Exception\FetchException;
use Tomaj\Scraper\Exception\ScraperException;
use Tomaj\Scraper\Parser\OgParser;
use Tomaj\Scraper\Scraper;
$base = $argv[1] ?? 'http://127.0.0.1:8405';
$scraper = new Scraper([
'connect_timeout' => 2,
'timeout' => 1,
'allow_redirects' => ['max' => 3],
'headers' => ['User-Agent' => 'ExampleBot/1.0'],
]);
$parsers = [new OgParser()];
function fetch(Scraper $scraper, string $url, array $parsers): void
{
$path = parse_url($url, PHP_URL_PATH) ?? $url;
try {
$meta = $scraper->parseUrl($url, $parsers);
printf("%-18s ok, title \"%s\"\n", $path, $meta->getTitle());
} catch (FetchException $e) {
// $e->url is the URL you passed, getPrevious() the Guzzle exception
printf("%-18s FetchException: %s\n", $path, reason($e->getPrevious()));
}
}
// The Guzzle exception classes differ between Guzzle 7 and 8; these checks work with both.
function reason(?Throwable $previous): string
{
return match (true) {
$previous instanceof TooManyRedirectsException => 'too many redirects',
$previous instanceof BadResponseException => 'HTTP ' . $previous->getResponse()->getStatusCode(),
$previous !== null && str_contains($previous->getMessage(), 'timed out') => 'timed out',
$previous !== null && str_contains($previous->getMessage(), 'cURL error 7:') => 'connection refused',
default => 'other error',
};
}
echo "== parseUrl() with a 1 s timeout and at most 3 redirects\n";
foreach (['/ok', '/moved', '/echo-user-agent', '/missing', '/error', '/slow', '/loop'] as $path) {
fetch($scraper, $base . $path, $parsers);
}
// nothing listens on this port: the connection is refused
fetch($scraper, 'http://127.0.0.1:9/closed-port', $parsers);
echo "\n== http_errors: false parses error pages instead of throwing\n";
$lenient = new Scraper(['timeout' => 1, 'http_errors' => false]);
fetch($lenient, $base . '/missing', $parsers);
echo "\n== allow_redirects: false returns the redirect response itself\n";
$noRedirects = new Scraper(['timeout' => 1, 'allow_redirects' => false]);
$meta = $noRedirects->parseUrl($base . '/moved', $parsers);
printf("%-18s ok, title %s, body %d bytes\n", '/moved', var_export($meta->getTitle(), true), strlen($noRedirects->getBody()));
echo "\n== catch every exception of the package with ScraperException\n";
try {
$scraper->parseUrl($base . '/error', $parsers);
} catch (ScraperException $e) {
// the message is "Cannot fetch <url>: " followed by the Guzzle message
echo get_class($e), "\n", explode(' resulted in', $e->getMessage())[0], "\n";
}Output
text
== parseUrl() with a 1 s timeout and at most 3 redirects
/ok ok, title "It works"
/moved ok, title "It works"
/echo-user-agent ok, title "ExampleBot/1.0"
/missing FetchException: HTTP 404
/error FetchException: HTTP 500
/slow FetchException: timed out
/loop FetchException: too many redirects
/closed-port FetchException: connection refused
== http_errors: false parses error pages instead of throwing
/missing ok, title "Page not found | Fixture site"
== allow_redirects: false returns the redirect response itself
/moved ok, title NULL, body 0 bytes
== catch every exception of the package with ScraperException
Tomaj\Scraper\Exception\FetchException
Cannot fetch "http://127.0.0.1:8405/error": Server error: `GET http://127.0.0.1:8405/error`What to notice
- One exception type. HTTP errors, the timeout, the redirect loop and the refused connection are all
FetchException.$e->urlis the URL you asked for;getPrevious()is the Guzzle exception with the details. - Guzzle 7 and 8. The Guzzle exception classes differ between the versions (a timeout is a
ConnectExceptionin Guzzle 7 and aNetworkTimeoutExceptionin Guzzle 8). Thereason()function checksBadResponseExceptionandTooManyRedirectsException, which both have; the example gives the same output with both versions. - Your headers are sent.
/echo-user-agentshows theUser-Agentfrom the options. http_errors: falseturns the 404 into a normal result: the error page is parsed and its title returned.allow_redirects: falsereturns the301response itself: an empty body, so nothing is found.ScraperExceptioncatches every exception of the package.
What CI checks
Each line of the output: the redirect followed, the custom User-Agent, the status of the 404 and 500, the timeout after 1 second, the redirect limit, the refused connection and the exception message format.