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.