Thanks to Jaypan's and 4uk4's comments, I found a way to do this.
The answer to "Can I add an event subscriber in a Drush command? (Get drush to subscribe to events?)" is no, you cannot.
However, if you change the question to "Can I add an event subscriber to a Drupal module that subscribes to an event and does specific processing if Drush was used to initiate the event?" the answer is yes.
Here's an example. This adds an event subscriber to the Feeds module that throws an exception if and only if drush was used to initiate an import which subsequently failed.
<?php
namespace Drupal\feeds\EventSubscriber;
use Drupal\feeds\Event\FeedsEvents;
use Drupal\feeds\Event\ImportFinishedEvent;
use Drupal\feeds\Exception\FeedsDrushException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event listener that throws an exception if a drush-initiated import fails.
*/
class DrushImportExceptionSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[FeedsEvents::IMPORT_FINISHED][] = 'onImportFinished';
return $events;
}
/**
* Throws an exception if any drush-initiated imports failed.
*/
public function onImportFinished(ImportFinishedEvent $event, string $event_name, EventDispatcherInterface $dispatcher): void {
// Process only if the import was initiated by drush.
if (PHP_SAPI === 'cli' && class_exists('\Drush\Drush')) {
$feed = $event->getFeed();
$process_state = $feed->getState('process');
$failed_count = $process_state->failed;
if ($failed_count > 0) {
$feed_id = $feed->id();
throw new FeedsDrushException("Feed with id $feed_id failed to import $failed_count items!");
}
}
}
}