codeigniterexceptionsolrsolarium

How to handle solr disconnection in codeigniter


I implement search functionalities with the help of solr via solarium in CodeIgniter.

I'm starting my website without solr connection (i.e. If the solr connection is stopped), My website throws the below warning message,

An uncaught Exception was encountered

Type: Solarium\Exception\HttpException

Message: Solr HTTP error: HTTP request failed, Failed to connect to localhost port 8983: Connection refused

Filename: C:\wamp\www\project-folder\project-name\vendor\solarium\solarium\src\Core\Client\Adapter\Curl.php

Line Number: 170

My doubt is if any chance to add exception handling in solr connection.

That means, If solr status is true it works as it is. If the solr status is false (Not in connection) the error warning is not displayed.

This above scenario is possible or not by using exception handling.

Update

My controller page,

        function __construct()
        {
          parent::__construct();
          $this->config->load('solarium');
          $this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
        }

        public function solrQuery() 
        {
            $query = $this->client->createSelect();

            $query->setStart(0)->setRows(1000);

            // get the facetset component
            $facetSet = $query->getFacetSet();

            $facetSet->createFacetField('product_category_1')->setField('product_category_1');

            $categories_data = $this->client->select($query);
        }


Solution

  • Surround the relevant bits of code that throw exceptions in a try-catch block like so:

    function __construct() {
        parent::__construct();
        $this->config->load('solarium');
        try {
            $this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
        } catch (\Exception $e) {
            show_error($e->getMessage());
        }
    }
    
    public function solrQuery() {
        try {
            $query = $this->client->createSelect();
    
            $query->setStart(0)->setRows(1000);
    
            // get the facetset component
            $facetSet = $query->getFacetSet();
    
            $facetSet->createFacetField('product_category_1')->setField('product_category_1');
    
            $categories_data = $this->client->select($query);
        } catch (\Exception $e) {
            show_error($e->getMessage());
        }
    }
    

    Of course you don't have yo use show_error() and can instead return false, or set your own headers and your own message.