7
7
use NotificationChannels \Telegram \Contracts \TelegramSenderContract ;
8
8
use NotificationChannels \Telegram \Exceptions \CouldNotSendNotification ;
9
9
use Psr \Http \Message \ResponseInterface ;
10
+ use Closure ;
10
11
11
12
/**
12
13
* Class TelegramMessage.
@@ -15,6 +16,7 @@ class TelegramMessage extends TelegramBase implements TelegramSenderContract
15
16
{
16
17
/** @var int Message Chunk Size */
17
18
public int $ chunkSize = 0 ;
19
+ public ?Closure $ exceptionHandler = null ;
18
20
19
21
public function __construct (string $ content = '' )
20
22
{
@@ -82,6 +84,22 @@ public function view(string $view, array $data = [], array $mergeData = []): sel
82
84
return $ this ->content (View::make ($ view , $ data , $ mergeData )->render ());
83
85
}
84
86
87
+ /**
88
+ * Registers a callback function to handle exceptions.
89
+ *
90
+ * This method allows you to define a custom error handler,
91
+ * which will be invoked if an exception occurs during the
92
+ * notification process. The callback must be a valid Closure.
93
+ *
94
+ * @param Closure $callback The closure that will handle exceptions.
95
+ * @return self
96
+ */
97
+ public function onError (Closure $ callback ): self
98
+ {
99
+ $ this ->exceptionHandler = $ callback ;
100
+ return $ this ;
101
+ }
102
+
85
103
/**
86
104
* Chunk message to given size.
87
105
*
@@ -110,11 +128,19 @@ public function send(): ResponseInterface|array|null
110
128
{
111
129
$ params = $ this ->toArray ();
112
130
113
- if ($ this ->shouldChunk ()) {
114
- return $ this ->sendChunkedMessage ($ params );
131
+ try {
132
+ if ($ this ->shouldChunk ()) {
133
+ return $ this ->sendChunkedMessage ($ params );
134
+ }
135
+
136
+ return $ this ->telegram ->sendMessage ($ params );
137
+ } catch (Exception $ exception ) {
138
+ if (! $ this ->exceptionHandler ) {
139
+ throw $ exception ;
140
+ }
141
+
142
+ $ this ->exceptionHandler ($ exception );
115
143
}
116
-
117
- return $ this ->telegram ->sendMessage ($ params );
118
144
}
119
145
120
146
/**
0 commit comments