8 – Check if the connection to the database is available

I have 2 databases, the first one with Drupal and the second one with external data. In a controller I want to read data from that second database and display it.

As the external database can be available or not, is there any method to check if the connection is available or not?

My code is working, but if the DB is not available (or unset) I get the following error:

DrupalCoreDatabaseConnectionNotDefinedException: The specified
database connection is not defined: schedules in
DrupalCoreDatabaseDatabase::openConnection() (line 364 of
core/lib/Drupal/Core/Database/Database.php).

Code:

abstract class AbstractSchedulesRepository {

  /**
   * Schedules repository target.
   */
  public const SCHEDULES_REPOSITORY_TARGET_DATABASE = 'default';

  /**
   * Schedules repository key.
   */
  public const SCHEDULES_REPOSITORY_KEY_DATABASE = 'schedules';

  /**
   * DrupalschedulesRepositorySchedulesCache definition.
   *
   * @var DrupalschedulesCacheSchedulesCache
   */
  protected $schedulesCache;

  /**
   * DrupalCoreLanguageLanguageManager definition.
   *
   * @var DrupalCoreLanguageLanguageManager
   */
  protected $languageManager;

  /**
   * DrupalCoreDatabaseConnection definition.
   *
   * @var DrupalCoreDatabaseConnection
   */
  protected $connection;

  /**
   * Constructor.
   *
   * @param DrupalschedulesCacheSchedulesCache $schedulesCache
   *   Schedules cache.
   * @param DrupalCoreLanguageLanguageManager $languageManager
   *   Language manager.
   */
  public function __construct(SchedulesCache $schedulesCache, LanguageManager $languageManager) {
    $this->schedulesCache  = $schedulesCache;
    $this->languageManager = $languageManager;
    $this->connection      = Database::getConnection(self::SCHEDULES_REPOSITORY_TARGET_DATABASE, self::SCHEDULES_REPOSITORY_KEY_DATABASE);
  }