This code in a form to a non-existing URL crashes the site and outputs The website encountered an unexpected error. Please try again later.. The real code is at http://cgit.drupalcode.org/piwik/tree/src/Form/PiwikAdminSettingsForm.ph...

    $url = 'http://www.example.com/test/';
    try {
      $result = \Drupal::httpClient()->get($url);
      if ($result->getStatusCode() != 200) {
        $form_state->setErrorByName('piwik_url_http', t('The validation of "@url" failed with error "@error" (HTTP code @code).', [
          '@url' => UrlHelper::filterBadProtocol($url),
          '@error' => $result->getReasonPhrase(),
          '@code' => $result->getStatusCode()
        ]));
      }
    catch (RequestException $exception) {
      return FALSE;
    }

The error should be catched and the normal page need to be shown.

Comments

hass created an issue. See original summary.

dawehner’s picture

Well, do you have the right use statement?

hass’s picture

\Drupal::httpClient() does not require "use" as it is a service!?

See http://cgit.drupalcode.org/piwik/tree/src/Form/PiwikAdminSettingsForm.ph...

hass’s picture

Title: Cannot catch Guzzle requests » Cannot try/catch Guzzle request exceptions
hass’s picture

Issue summary: View changes
dawehner’s picture

Category: Bug report » Support request
Status: Active » Fixed

It is simply how PHP work, if you use an exception class you also need to put a "use" statement in order to use it.

hass’s picture

Status: Fixed » Active

Can you take a look into the piwik code, please?

It does not look like there is a class missing. The error happens because Guzzle fires an exception on a http status code 404. At least this is what I see in dblog logged.

larowlan’s picture

There is also ClientException

dawehner’s picture

Issue summary: View changes

@hass
These are the use statements

use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

you use in that particular file.

\GuzzleHttp\Exception\RequestException is the one you need as well.
You can also specify $options['http_errors'] = FALSE when running ->get() which will stop firing the exception.

hass’s picture

Status: Active » Fixed

*OMG*. Got it... that works. Many thanks.

dawehner’s picture

*OMG*. Got it... that works. Many thanks.

No worries :)

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.