diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f593639..aac10bbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * Allow to use imported class in task from remote import * Do not load task from `vendor` directory * Add `context()` function in expression language to enable a task +* Better handle notification errors and exceptions * Deprecate `Castor\GlobalHelper` class. There are no replacements. Use raw functions instead * Deprecate `AfterApplicationInitializationEvent` event. Use diff --git a/src/Helper/Notifier.php b/src/Helper/Notifier.php index bd5fda01..6e81f7c1 100644 --- a/src/Helper/Notifier.php +++ b/src/Helper/Notifier.php @@ -2,13 +2,17 @@ namespace Castor\Helper; +use Joli\JoliNotif\Exception\InvalidNotificationException; use Joli\JoliNotif\Notification; use Joli\JoliNotif\Notifier as JoliNotifier; +use Joli\JoliNotif\Notifier\NullNotifier; +use Psr\Log\LoggerInterface; class Notifier { public function __construct( - private JoliNotifier $notifier + private JoliNotifier $notifier, + private LoggerInterface $logger, ) { } @@ -19,6 +23,22 @@ public function send(string $message): void ->setBody($message) ; - $this->notifier->send($notification); + if ($this->notifier instanceof NullNotifier) { + $this->logger->warning('No supported notifier found, notification not sent.'); + + return; + } + + try { + $success = $this->notifier->send($notification); + + if (!$success) { + $this->logger->error('Failed to send notification.'); + } + } catch (InvalidNotificationException $e) { + throw $e; + } catch (\Throwable $e) { + $this->logger->error('Failed to send notification: ' . $e->getMessage()); + } } } diff --git a/tests/Helper/OutputCleaner.php b/tests/Helper/OutputCleaner.php index d1032adf..a5cea7c9 100644 --- a/tests/Helper/OutputCleaner.php +++ b/tests/Helper/OutputCleaner.php @@ -28,6 +28,9 @@ public static function cleanOutput(string $string): string // Clean the warning on tasks when remote imports are disabled $string = preg_replace('{hh:mm:ss WARNING \[castor\] Could not import "[\w:/\.-]*" in "[\w:/\.-]*" on line \d+. Reason: Remote imports are disabled\.}m', '', $string); + // Fix notification logs + $string = preg_replace('{hh:mm:ss ERROR \[castor\] Failed to send notification\.}m', '', $string); + // Avoid spacing issues $string = ltrim($string, "\n"); // Trim output start to avoid empty lines (like after removing remote import warnings) $string = preg_replace('/ +$/m', '', $string); // Remove trailing space