Score:2

How do I return an empty build array and log an error?

pe flag

I am using the following code for a block.

class WeatherBlock extends BlockBase implements ContainerFactoryPluginInterface {
  
  // Dependency injection code
  
  public function getCity() {
    $ip = '193.62.157.66';
    try {
      $response_ip = $this->httpClient->get('http://ip-api.com/json/' . $ip);
      $response_data_ip = $response_ip->getBody();
      $data_ip = json_decode($response_data_ip);
      if ($data_ip->status == 'success') {
        return $data_ip->city;
      }
      else {
        return $this->configFactory->get('sydneypro_weather.settings')->get('weather_city');
      }
    }
    catch (RequestException $e) {
      return FALSE;
    }
  }

  public function build() {
    $client = $this->httpClient;
    $api_key = $this->configFactory->get('sydneypro_weather.settings')->get('weather_api_key');
    $cid = 'sydneypro_weather';
    if (empty($api_key)) {
      return [
        '#type' => 'markup',
        '#markup' => $this->t('Please enter your API key in the Admin panel to see the weather'),
      ];
    }
    try {
      if ($cache = $this->cacheBackend->get($cid)) {
        $data = $cache->data;
      }
      else {
        $response = $client->get('http://api.openweathermap.org/data/2.5/weather?q=' . $this->getCity() . ',&appid=' . $api_key . '&units=metric');
        $response_data = $response->getBody();
        $data = json_decode($response_data);
        $this->cacheBackend->set($cid, $data, $this->time->getRequestTime() + 21600);
      }
      
      $build = [
        '#theme' => 'weather_block',
        '#data' => $data,
        '#attached' => [
          'library' => [
            'sydneypro_weather/sydneypro_weather',
          ],
        ],
      ];
      return $build;
    }

    catch (RequestException $e) {
      return [
        '#markup' => Markup::create('<h1>Sorry, no data available</h1>'),
      ];
    }
  }

}

The configuration is ignored using the Config ignore module; when I deploy the website to another environment, the module configuration (which is ignored) isn't created in the database during drush cim. When the configuration is missing, I need to return an empty build array and log an error.

I looked at several examples where the logger is called using \Drupal::logger(' ')->error(' ', []);. I don't understand how I could return an empty build array and log an error, and where to insert all this in the code.

apaderno avatar
us flag
Essentially, you don't know which parameter to pass to [`\Drupal::logger()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3Alogger/9.3.x) and which parameters to pass to the [`error()`](https://api.drupal.org/api/drupal/vendor%21psr%21log%21Psr%21Log%21LoggerInterface.php/function/LoggerInterface%3A%3Aerror/9.3.x) method. What exactly don't you understand? Without a very specific question, we would just say what the documentation already says.
apaderno avatar
us flag
As for *I don't understand how I could return an empty build array and log an error*, you first call `Drupal::logger()->error()` with the right parameters and then return an empty array. This is how PHP works and not something Drupal-specific.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.