3

I use search_api_solr with a server-based Solr installation. Works fine. For reasons I won't explain, the Solr service is stopped sometimes. If a user does a search while Solr is stopped, they crash with "The website encountered an unexpected error."

The error log says "Drupal\search_api_solr\SearchApiSolrException: An error occurred while trying to search with Solr: Solr endpoint http://localhost:8983/ unreachable or returned unexpected response code "0"." No surprise, since the service is stopped.

How can I trap this error and display a "Search isn't working" page instead of crashing? Seems like there should be a way to intercept it, but I haven't figured it out.

4

Based on the comment by @4k4 and post at https://drupal.stackexchange.com/a/235942/70681 and further reading, I used my existing custom module (rsc) to solve the problem as follows:

In modules/custom/rsc/rsc.services.yml

services:
  rsc.event.SolrException:
    class: Drupal\rsc\EventSubscriber\rscSolrException
    tags:
      - { name: event_subscriber }

In modules/custom/rsc/src/EventSubscriber/rscSolrException.php

<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\search_api_solr\SearchApiSolrException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class rscSolrException implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof SearchApiSolrException) {
      $event->setResponse(new RedirectResponse('/search-not-working'));
    }
  }
}

When a Solr exception occurs, users are redirected to the search-not-working page instead of to "The website encountered an unexpected error." Much nicer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.