1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Error handlers, types, and contexts.
//!
//! Dyncord supports modular, layered error handling. For error handling to work properly, though,
//! you need to keep one rule in mind: **Do not let your code panic.** Panics break error handling,
//! so if you panic, God save you. Okay, maybe not God save you, but any handlers pending to run
//! for the current error queue won't run, which is not nice.
//!
//! # Quick Start
//!
//! Error handling is done the same way everything else is done on Dyncord: using async functions.
//! To define your first error handler, create the following function:
//!
//! ```
//! async fn handle_error(ctx: ErrorContext, error: DyncordError) {
//! // Error-handling code here.
//! }
//! ```
//!
//! Every part of dyncord that allows you to pass a custom function as an argument to handle
//! something also supports error handling. For example, to handle bot-wide errors,
//! [`Bot`](crate::Bot) has a [`Bot::on_error`](crate::Bot::on_error) function that can be used one
//! or many times, once per error handler.
//!
//! Error handling is done in layers. Let's suppose we want to handle `MessageCreate` events.
//! However, what we're doing inside that handler is querying a database, and such query can fail.
//!
//! ```
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! An error occurred with the database: {0}")]
//! struct DatabaseError(&'static str);
//!
//! async fn on_message_create(ctx: EventContext<(), MessageCreate>) -> Result<(), DatabaseError> {
//! Err(DatabaseError("We couldn't connect to the database. In fact, we didn't even try. Good luck."))
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let bot = Bot::new(())
//! .intents(Intents::GUILD_MESSAGES)
//! .on_event(On::message_create(on_message_create));
//!
//! bot.run("token").await.unwrap();
//! }
//! ```
//!
//! > *Note: Yes! Event handlers, like command handlers and error handlers, can return an arbitrary
//! > `Result<T, E>`. `Err(E)` will fire error handlers.*
//!
//! When we run our bot, events will start flowing in. Our event handler fails on every call, but
//! they go unnoticed and that sucks. Let's add the error handler we created in the first example.
//!
//! ```
//! async fn on_error(ctx: ErrorContext, error: DyncordError) {
//! println!("Oh no! An error occurred: {error}");
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let bot = Bot::new(())
//! .intents(Intents::GUILD_MESSAGES)
//! .on_event(On::message_create(on_message_create))
//! .on_error(on_error);
//!
//! bot.run("token").await.unwrap();
//! }
//! ```
//!
//! Run your code again, and you'll see that whenever an event comes in, the error handler gets
//! fired and the error is logged. Great.
//!
//! Now, what if we add a prefixed command to our bot that also fails every time? Let's try it out.
//!
//! ```
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! A completely-unexpected error occurred when the user run the fail command: {0}")]
//! struct FailError(String);
//!
//! async fn fail(ctx: PrefixedContext, message: String) -> Result<(), FailError> {
//! Err(FailError(message))
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail))
//! .on_event(On::message_create(on_message_create))
//! .on_error(on_error);
//!
//! bot.run("token").await.unwrap();
//! }
//! ```
//!
//! Rerun your bot and try the `.fail` command. You'll see it get logged successfully. What if you
//! run `.fail` without any arguments? It'll also get logged, this time as a command error.
//!
//! # Scoped Error Handling
//!
//! This is working well, it logs everything, but what if we want to have an error handler that
//! only runs on command errors? We want to handle `.fail`'s errors differently than the rest.
//!
//! Let's make our `on_error` handler only handle the `.fail` command's errors.
//!
//! ```
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail).on_error(on_error)) // Move the .on_error() to this line.
//! .on_event(On::message_create(on_message_create));
//!
//! bot.run("token").await.unwrap();
//! ```
//!
//! Try running your bot again. You'll see that now, errors returned by the event handler no longer
//! get logged but `.fail` ones still do. Good!
//!
//! You can do the same with the event handler. Let's move our error handler to the event handler.
//!
//! ```
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail).on_error(on_error))
//! .on_event(On::message_create(on_message_create).on_error(on_error)); // Add the .on_error() to this line.
//!
//! bot.run("token").await.unwrap();
//! ```
//!
//! Rerun your bot and you'll see that now error logging is back to how we started. You can add
//! error handlers to specific commands, command groups, events, and bot-wide. The same handlers
//! can be recycled, too.
//!
//! # Failing Error Handlers and Layers
//!
//! Even error handlers can fail. What when they do? Are they immune to error handling? In dyncord,
//! handlers can catch errors raised by more-specific error handlers, and also catch errors that
//! more-specific error handlers failed to handle.
//!
//! For example, we may want to store error logs in a database. Such thing, as in our previous
//! example, can fail. In such case, we want to just log the error onto the terminal.
//!
//! Our first error handler looks like this:
//!
//! ```
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! A completely-unexpected error occurred when the user run the fail command: {0}")]
//! struct FailError(String);
//!
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! An error occurred with the database: {0}")]
//! struct DatabaseError(&'static str);
//!
//! async fn fail(ctx: PrefixedContext, message: String) -> Result<(), FailError> {
//! Err(FailError(message))
//! }
//!
//! async fn log_to_database(_ctx: ErrorContext, _error: DyncordError) -> Result<(), DatabaseError> {
//! Err(DatabaseError("Oh no! We didn't try to save anything, and somehow nothing got saved. An error? Are we getting hacked? President is it you?"))
//! }
//!
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail).on_error(log_to_database));
//!
//! bot.run("token").await.unwrap();
//! ```
//!
//! Great. But if you look closely, you'll see that our `log_to_database` error handler never
//! succeeds for mysterious reasons. That means that now we have errors silently occurring and
//! disappearing.
//!
//! As we said, we want to log to the terminal when we can't log to the database. Let's make a
//! simple error handler to do such thing.
//!
//! ```
//! async fn log_to_terminal(_ctx: ErrorContext, error: DyncordError) {
//! println!("ERORR: {error}");
//! }
//! ```
//!
//! Now, let's make that one a [`Bot`](crate::Bot)-level error handler.
//!
//! ```
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! A completely-unexpected error occurred when the user run the fail command: {0}")]
//! struct FailError(String);
//!
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! An error occurred with the database: {0}")]
//! struct DatabaseError(&'static str);
//!
//! async fn fail(ctx: PrefixedContext, message: String) -> Result<(), FailError> {
//! Err(FailError(message))
//! }
//!
//! async fn log_to_database(_ctx: ErrorContext, _error: DyncordError) -> Result<(), DatabaseError> {
//! Err(DatabaseError("Oh no! We didn't try to save anything, and somehow nothing got saved. An error? Are we getting hacked? President is it you?"))
//! }
//!
//! async fn log_to_terminal(_ctx: ErrorContext, error: DyncordError) {
//! println!("ERORR: {error}");
//! }
//!
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail).on_error(log_to_database))
//! .on_error(log_to_terminal); // Add this line.
//!
//! bot.run("token").await.unwrap();
//! ```
//!
//! Try running your bot and running the `.fail` command. You'll see two errors being logged onto
//! the terminal. Well done.
//!
//! If you're asking yourself why two errors, the answer is simple: `FailError` failed to be
//! logged into the database, but we don't want it disappearing because of it. It's passed to the
//! next most-specific error handler there is, in this case `log_to_terminal`. `DatabaseError` also
//! has to be handled, so it's also passed down to `log_to_terminal`. That makes it two log lines.
//!
//! As stated before, dyncord's error handling is layered. Any errors not handled by the first
//! layer will be passed down to the next available layer, and if such layer fails to handle it,
//! it'll be passed down to the next layer until either the error gets handled or no more layers
//! are available to handle it.
//!
//! Layers go from most-specific to least-specific error handler. A bot-wide error handler is
//! less specific than a command-specific error handler, and a group-wide error handler is more
//! specific than a bot-wide error handler but less-specific than a command-specific error handler.
//!
//! # Intentionally Ignoring Errors
//!
//! Usually, you may find yourself making error handlers for only a specific kind or group of
//! errors. You want to let some errors pass down, but it's not an error to do so so you don't want
//! to return a custom error to force the error to be handled by a less-specific layer. That would
//! also introduce a special case not to handle your custom "pass down this error" error, it gets
//! ugly fast.
//!
//! Luckily, dyncord has a built-in way of doing this while keeping your happiness intact. Make the
//! error handler return `Result<T, ErrorHandlerError>`, and when you don't want to handle an
//! error, just return [`ErrorHandlerError::NotHandled`].
//!
//! ```
//! /// An error handler that does not handle any errors.
//! async fn on_error_not_handle(ctx: ErrorContext, error: DyncordError) -> Result<(), ErrorHandlerError> {
//! Err(ErrorHandlerError::NotHandled)
//! }
//! ```
//!
//! If you add a logging error handler on a layer lower to that, you'll see that the original error
//! gets logged but no `ErrorHandlerError` log can be seen. That's because
//! [`ErrorHandlerError::NotHandled`] means you chose not to handle such error, and therefore it's
//! not *actually* an error.
//!
//! # Multi-Handler Error Handler Layers
//!
//! Dyncord also supports having multiple error handlers per layer. In such cases, when an error
//! reaches a layer, **all error handlers in such layer are called with the error**.
//!
//! To define multiple error handlers per layer, just chain `.on_error()` calls. For example,
//!
//! ```
//! async fn handler_1(ctx: ErrorContext, error: DyncordError) {
//! println!("Handler 1 is running... {error}");
//! }
//!
//! async fn handler_2(ctx: ErrorContext, error: DyncordError) {
//! println!("Handler 2 is running... {error}");
//! }
//!
//! let bot = Bot::new(())
//! .on_error(handler_1)
//! .on_error(handler_2);
//! ```
//!
//! Whenever an error reaches the bot-wide layer, both error handlers will be called. It doesn't
//! matter whether one of those succeeds.
//!
//! When more than one handler is in a layer, for an error to be passed to the next layer no
//! handler in the current layer must have succeeded to handle the error.
//!
//! For example, in a more complex event handler situation, events could be passed down as follows:
//!
//! ```text
//! handler_1(error) -> Always fails
//! handler_2(error) -> Always doesn't handle error
//! handler_3(error) -> Always succeeds only on command errors
//! handler_4(error) -> Always fails
//! handler_5(error) -> Always fails
//!
//! command() -> Error
//!
//! handle(ctx, error, [[handler_1, handler_2], [handler_3, handler_4], [handler_5]]);
//!
//! handler_1(error) -> Fails
//! handler_2(error) -> Didn't handle
//!
//! handler_3(handler_1_error) -> Didn't handle
//! handler_3(error) -> Succeess!
//! handler_4(handler_1_error) -> Fails
//! handler_4(error) -> Fails
//!
//! handler_5(handler_1_error) -> Fails
//! handler_5(handler_4_error_1) -> Fails
//! handler_5(handler_4_error_2) -> Fails
//! ```
//!
//! As you can see, `handler_1`'s error gets passed all the way down because no handler in the
//! middle layers handles it properly. The original error gets properly handled by `handler_3`, so
//! that error stops getting propagated. `handler_4` raises an error twice, one per call, so
//! `handler_5` ends up handling `handler_1`'s error and both of `handler_4`'s errors. `handler_5`
//! fails, but there's no more error handler layers so 6 errors go unhandled.
//!
//! # Downcasting to Custom Errors
//!
//! All error handlers are required to take `DyncordError` as an error. That's useful for basic
//! logging, but what when you want to act differently based on the error type you actually
//! returned?
//!
//! [`DyncordError`] has a [`downcast()`](DyncordError::downcast) associated function that does the
//! error pattern matching and downcasting for you all in one go, without needing to manually match
//! and try to downcast on every possible variant. Spoiler: [`DyncordError`] gets quite nested.
//!
//! Downcasting is simple, take the following example
//!
//! ```
//! #[derive(Debug, thiserror::Error)]
//! #[error("Oh no! A completely-unexpected error occurred when the user run the fail command: {0}")]
//! struct FailError(String);
//!
//! async fn fail(ctx: PrefixedContext, message: String) -> Result<(), FailError> {
//! Err(FailError(message))
//! }
//!
//! async fn on_fail_error(_ctx: ErrorContext, error: DyncordError) {
//! if let Some(error) = error.downcast::<FailError>() { // Here.
//! println!("ERROR: {}", error.0);
//! }
//! }
//!
//! let bot = Bot::new(())
//! .with_prefix(".")
//! .intents(Intents::GUILD_MESSAGES)
//! .intents(Intents::MESSAGE_CONTENT)
//! .command(Command::prefixed("fail", fail).on_error(on_fail_error));
//!
//! bot.run("token").await.unwrap();
//! ```
//!
//! Given you're allowed to return any error type you want from your handlers, dyncord has to erase
//! the type from your error to store it into a generic [`DyncordError`]. Downcasting here attempts
//! to get the type-erased error and see if it matches the error type you gave it. If it does, then
//! it returns the value to you in the `Some()`.
//!
//! # Original Error Contexts
//!
//! Many times, you want to let the user know an error happened. However, [`ErrorContext`] is
//! neither [`PrefixedContext`] nor [`SlashContext`] nor any command type-specific context type, so
//! you can't directly tell the user an error occurred.
//!
//! [`ErrorContext`] has an [`original`](ErrorContext::original) field that holds the original
//! context type. You could match against it to tell the user an error occurred.
//!
//! ```
//! async fn on_error_notify_user(ctx: ErrorContext, _error: DyncordError) -> Result<(), ErrorHandlerError> {
//! match ctx.original {
//! ErrorOriginalContext::PrefixedContext(ctx) => {
//! let _ = ctx.send("Oh no! An error occurred.").await.map_err(ErrorHandlerError::new)?;
//! },
//! ErrorOriginalContext::SlashContext(ctx) => {
//! ctx.respond("Oh no! An error occurred.").await.map_err(ErrorHandlerError::new)?;
//! },
//! _ => {
//! return Err(ErrorHandlerError::NotHandled)
//! }
//! };
//!
//! Ok(())
//! }
//! ```
//!
//! However, that's ugly. That's why you can use [`ErrorContext::send`] instead, which is similar
//! to the example above but cleaner.
//!
//! ```
//! async fn on_error_notify_user(ctx: ErrorContext, _error: DyncordError) -> Result<(), ErrorHandlerError> {
//! ctx.send("Oh no! An error occurred.").await?;
//!
//! Ok(())
//! }
//! ```
//!
//! [`ErrorContext::send`] is the same as [`PrefixedContext::send`] when the error was returned by
//! a prefixed-command handler, the same as [`SlashContext::respond`] when the error was returned
//! by a slash-command handler, and the same as [`MessageContext::respond`] when the error was
//! returned by a message command.
//!
//! The only difference with the first example matching on `ctx.original` is that when the message
//! is not sent, it doesn't return [`ErrorHandlerError::NotHandled`], rather `Ok(false)`.
use Any;
use Error;
use PhantomData;
use Arc;
use Event;
use crate;
use crateMessageContext;
use cratePrefixedContext;
use cratePrefixesContext;
use crateSlashContext;
use crateEventContext;
use crateHandle;
use crateStateBound;
use crateDynFuture;
/// A top-level error type for handle-able errors that occur while the bot is running.
/// Context passed to error handlers when an error occurs.
/// Wraps the original context type in an enum to pass it down to event handlers.
/// The result type all error handlers' results are normalized to.
pub type ErrorHandlerResult = ;
/// An error occurred while an error handler was being ran, or the handler chose not to handle the
/// error passed.
/// Normalizes an error handler's return value into an [`ErrorHandlerResult`].
/// A trait implemented by error handler functions.
/// A trait implemented by error handler wrappers that erases the specific error type being
/// handled.
/// Wraps an error handler function with a phantom error type and a phantom dummy type.
pub
/// Handles an error and any errors that occur while handling such error.
///
/// The handlers are passed to this function in layers. All handlers within the first layer will be
/// called to handle the error. If none can successfully handle the error, the error is then passed
/// to be handled by all error handlers in the next layer. This repeats until either all errors can
/// be handled or no more layers remain.
///
/// If a handler itself returns an error, that error will *also* be passed to the next layers's
/// handlers. For example:
///
/// ```text
/// handler_1(error) -> Always doesn't handle error
/// handler_2(error) -> Always fails
/// handler_3(error) -> Always doesn't handle error
/// handler_4(error) -> Always succeeds
/// handler_5(error) -> Always succeeds
///
/// handle(ctx, error, [[handler_1, handler_2], [handler_3, handler_4, handler_5]]);
///
/// handler_1(error) -> Didn't handle
/// handler_2(error) -> Fails
///
/// None could handle the error within the first group, and handler_2 returned yet another error
/// that must be handled.
///
/// handler_3(handler_2_error) -> Didn't handle
/// handler_3(error) -> Didn't handle
/// handler_4(handler_2_error) -> Success!
/// handler_4(error) -> Success!
/// handler_5(handler_2_error) -> Success!
/// handler_5(error) -> Success!
/// ```
///
/// Note how `handler_4` doesn't stop `handler_5` from being called too. When a layer is being run,
/// all handlers in that layer get called for all the to-handle errors even if a handler in that
/// layer succeeds at handling the error. A handler succeeding to handle the erorr only means the
/// successfully-handled error won't be passed down to the next layer, if any.
///
/// Let's add even more handlers and layers for a more complex example.
///
/// ```text
/// handler_1(error) -> Always fails
/// handler_2(error) -> Always doesn't handle error
/// handler_3(error) -> Always succeeds only on command errors
/// handler_4(error) -> Always fails
/// handler_5(error) -> Always fails
///
/// command() -> Error
///
/// handle(ctx, error, [[handler_1, handler_2], [handler_3, handler_4], [handler_5]]);
///
/// handler_1(error) -> Fails
/// handler_2(error) -> Didn't handle
///
/// handler_3(handler_1_error) -> Didn't handle
/// handler_3(error) -> Succeess!
/// handler_4(handler_1_error) -> Fails
/// handler_4(error) -> Fails
///
/// handler_5(handler_1_error) -> Fails
/// handler_5(handler_4_error_1) -> Fails
/// handler_5(handler_4_error_2) -> Fails
/// ```
///
/// As you can see, `handler_1`'s error gets passed all the way down because no handler in the
/// middle layers handles it properly. The original error gets properly handled by `handler_3`, so
/// that error stops getting propagated. `handler_4` raises an error twice, one per call, so
/// `handler_5` ends up handling `handler_1`'s error and both of `handler_4`'s errors. `handler_5`
/// fails, but there's no more error handler layers so 6 errors go unhandled.
///
/// Arguments:
/// * `ctx` - The error handler context.
/// * `error` - The error to handle.
/// * `handlers` - The handlers to use to handle the error. Most specific error handler first.
pub async