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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! External API errors.

#![allow(clippy::multiple_inherent_impl)] // for `wasm_bindgen`

use std::borrow::Cow;

#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::wasm_bindgen;

use tracerr::{Trace, Traced};

use crate::{
    api::Error,
    connection,
    media::{
        self, EnumerateDevicesError, EnumerateDisplaysError,
        GetDisplayMediaError, GetUserMediaError, InitLocalTracksError,
        InvalidOutputAudioDeviceIdError, MicVolumeError,
    },
    peer::{
        sender::CreateError, InsertLocalTracksError, LocalMediaError,
        UpdateLocalStreamError,
    },
    platform, room,
    rpc::{rpc_session::ConnectionLostReason, ReconnectError, SessionError},
    utils::Caused,
};

/// Error thrown when the operation wasn't allowed by the current state of the
/// object.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct StateError {
    /// Message describing the problem.
    message: Cow<'static, str>,

    /// Stacktrace of this [`StateError`].
    trace: Trace,
}

impl StateError {
    /// Creates a new [`StateError`] with the provided `message` and `trace`.
    #[must_use]
    pub fn new<T: Into<Cow<'static, str>>>(message: T, trace: Trace) -> Self {
        Self {
            message: message.into(),
            trace,
        }
    }
}

#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl StateError {
    /// Returns message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns native stacktrace of this [`StateError`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Possible error kinds of a [`LocalMediaInitException`].
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum LocalMediaInitExceptionKind {
    /// Occurs if the [getUserMedia()][1] request failed.
    ///
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    GetUserMediaFailed,

    /// Occurs if the [getUserMedia()][1] request failed on getting audio
    /// track.
    ///
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    GetUserMediaAudioFailed,

    /// Occurs if the [getUserMedia()][1] request failed on getting video
    /// track.
    ///
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    GetUserMediaVideoFailed,

    /// Occurs if the [getDisplayMedia()][1] request failed.
    ///
    /// [1]: https://w3.org/TR/screen-capture/#dom-mediadevices-getdisplaymedia
    GetDisplayMediaFailed,

    /// Occurs when local track is [`ended`][1] right after [getUserMedia()][2]
    /// or [getDisplayMedia()][3] request.
    ///
    /// [1]: https://tinyurl.com/w3-streams#idl-def-MediaStreamTrackState.ended
    /// [2]: https://tinyurl.com/rnxcavf
    /// [3]: https://w3.org/TR/screen-capture#dom-mediadevices-getdisplaymedia
    LocalTrackIsEnded,
}

/// Exception thrown when accessing media devices.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct LocalMediaInitException {
    /// Concrete error kind of this [`LocalMediaInitException`].
    kind: LocalMediaInitExceptionKind,

    /// Error message describing the problem.
    message: Cow<'static, str>,

    /// [`platform::Error`] causing this [`LocalMediaInitException`].
    cause: Option<platform::Error>,

    /// Stacktrace of this [`LocalMediaInitException`].
    trace: Trace,
}

impl LocalMediaInitException {
    /// Creates a new [`LocalMediaInitException`] from the provided error
    /// `kind`, `message`, optional `cause` and `trace`.
    #[must_use]
    pub fn new<M: Into<Cow<'static, str>>>(
        kind: LocalMediaInitExceptionKind,
        message: M,
        cause: Option<platform::Error>,
        trace: Trace,
    ) -> Self {
        Self {
            kind,
            message: message.into(),
            cause,
            trace,
        }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl LocalMediaInitException {
    /// Returns concrete error kind of this [`LocalMediaInitException`].
    // false positive: destructors cannot be evaluated at compile-time
    #[allow(clippy::missing_const_for_fn)]
    #[must_use]
    pub fn kind(&self) -> LocalMediaInitExceptionKind {
        self.kind
    }

    /// Returns an error message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns [`platform::Error`] causing this [`LocalMediaInitException`].
    #[must_use]
    pub fn cause(&self) -> Option<platform::Error> {
        self.cause.clone()
    }

    /// Returns stacktrace of this [`LocalMediaInitException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Exception thrown when cannot get info of available media devices.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct EnumerateDevicesException {
    /// [`platform::Error`] causing this [`EnumerateDevicesException`].
    cause: platform::Error,

    /// Stacktrace of this [`EnumerateDevicesException`].
    trace: Trace,
}

impl EnumerateDevicesException {
    /// Creates a new [`EnumerateDevicesException`] from the provided error
    /// `cause` and `trace`.
    #[must_use]
    pub const fn new(cause: platform::Error, trace: Trace) -> Self {
        Self { cause, trace }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl EnumerateDevicesException {
    /// Returns [`platform::Error`] causing this [`EnumerateDevicesException`].
    #[must_use]
    pub fn cause(&self) -> platform::Error {
        self.cause.clone()
    }

    /// Returns stacktrace of this [`EnumerateDevicesException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Exception thrown when cannot change output audio device ID.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct InvalidOutputAudioDeviceIdException {
    /// Stacktrace of this [`InvalidOutputAudioDeviceIdException`].
    trace: Trace,
}

impl InvalidOutputAudioDeviceIdException {
    /// Creates a new [`InvalidOutputAudioDeviceIdException`] from the provided
    /// error [`Trace`].
    #[must_use]
    pub const fn new(trace: Trace) -> Self {
        Self { trace }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl InvalidOutputAudioDeviceIdException {
    /// Returns stacktrace of this [`InvalidOutputAudioDeviceIdException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Exception thrown when cannot interact with microphone volume.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct MicVolumeException {
    /// [`platform::Error`] causing this [`MicVolumeException`].
    cause: platform::Error,

    /// Stacktrace of this [`MicVolumeException`].
    trace: Trace,
}

impl MicVolumeException {
    /// Creates a new [`MicVolumeException`] from the provided error [`Trace`].
    #[must_use]
    pub const fn new(cause: platform::Error, trace: Trace) -> Self {
        Self { cause, trace }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl MicVolumeException {
    /// Returns the [`platform::Error`] causing this [`MicVolumeException`].
    #[must_use]
    pub fn cause(&self) -> platform::Error {
        self.cause.clone()
    }

    /// Returns stacktrace of this [`MicVolumeException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Possible error kinds of a [`RpcClientException`].
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum RpcClientExceptionKind {
    /// Connection with a server was lost.
    ///
    /// This usually means that some transport error occurred, so a client can
    /// continue performing reconnecting attempts.
    ConnectionLost,

    /// Could not authorize an RPC session.
    ///
    /// This usually means that authentication data a client provides is
    /// obsolete.
    AuthorizationFailed,

    /// RPC session has been finished. This is a terminal state.
    SessionFinished,
}

/// Exceptions thrown from a RPC client that implements messaging with media
/// server.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct RpcClientException {
    /// Concrete error kind of this [`RpcClientException`].
    kind: RpcClientExceptionKind,

    /// Error message describing the problem.
    message: Cow<'static, str>,

    /// [`platform::Error`] causing this [`RpcClientException`].
    cause: Option<platform::Error>,

    /// Stacktrace of this [`RpcClientException`].
    trace: Trace,
}

impl RpcClientException {
    /// Creates a new [`RpcClientException`] from the provided error `kind`,
    /// `message`, optional `cause` and `trace`.
    #[must_use]
    pub fn new<M: Into<Cow<'static, str>>>(
        kind: RpcClientExceptionKind,
        message: M,
        cause: Option<platform::Error>,
        trace: Trace,
    ) -> Self {
        Self {
            kind,
            message: message.into(),
            cause,
            trace,
        }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl RpcClientException {
    /// Returns concrete error kind of this [`RpcClientException`].
    #[allow(clippy::missing_const_for_fn)] // because of `wasm_bindgen`
    #[must_use]
    pub fn kind(&self) -> RpcClientExceptionKind {
        self.kind
    }

    /// Returns an error message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns [`platform::Error`] causing this [`RpcClientException`].
    #[must_use]
    pub fn cause(&self) -> Option<platform::Error> {
        self.cause.clone()
    }

    /// Returns stacktrace of this [`RpcClientException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Jason's internal exception.
///
/// This is either a programmatic error or some unexpected platform component
/// failure that cannot be handled in any way.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct InternalException {
    /// Error message describing the problem.
    message: Cow<'static, str>,

    /// [`platform::Error`] causing this [`RpcClientException`].
    cause: Option<platform::Error>,

    /// Stacktrace of this [`InternalException`].
    trace: Trace,
}

impl InternalException {
    /// Creates a new [`InternalException`] from the provided error `message`,
    /// `trace` and an optional `cause`.
    #[must_use]
    pub fn new<T: Into<Cow<'static, str>>>(
        message: T,
        cause: Option<platform::Error>,
        trace: Trace,
    ) -> Self {
        Self {
            message: message.into(),
            trace,
            cause,
        }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl InternalException {
    /// Returns an error message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns [`platform::Error`] causing this [`RpcClientException`].
    #[must_use]
    pub fn cause(&self) -> Option<platform::Error> {
        self.cause.clone()
    }

    /// Returns stacktrace of this [`InternalException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }
}

/// Exception thrown when a string or some other data doesn't have an expected
/// format and cannot be parsed or processed.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct FormatException(Cow<'static, str>);

impl FormatException {
    /// Creates a new [`FormatException`] with the provided `message` describing
    /// the problem.
    #[must_use]
    pub fn new<T: Into<Cow<'static, str>>>(message: T) -> Self {
        Self(message.into())
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl FormatException {
    /// Returns an error message describing of the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.0.to_string()
    }
}

/// Kind of a [`MediaStateTransitionException`].
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Clone, Copy, Debug)]
pub enum MediaStateTransitionExceptionKind {
    /// Media state of a [`Sender`] transits to an opposite of the requested
    /// one.
    ///
    /// [`Sender`]: crate::peer::media::Sender
    OppositeState,

    /// Requested state transition is not allowed by [`Sender`]'s settings.
    ///
    /// [`Sender`]: crate::peer::media::Sender
    ProhibitedState,
}

/// Exception thrown when the requested media state transition could not be
/// performed.
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct MediaStateTransitionException {
    /// Error message describing the problem.
    message: Cow<'static, str>,

    /// Concrete error kind of this [`MediaStateTransitionException`].
    kind: MediaStateTransitionExceptionKind,

    /// Stacktrace of this [`MediaStateTransitionException`].
    trace: Trace,
}

impl MediaStateTransitionException {
    /// Creates a new [`MediaStateTransitionException`] from the provided error
    /// `message` and `trace`.
    #[must_use]
    pub fn new<T: Into<Cow<'static, str>>>(
        message: T,
        trace: Trace,
        kind: MediaStateTransitionExceptionKind,
    ) -> Self {
        Self {
            message: message.into(),
            trace,
            kind,
        }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl MediaStateTransitionException {
    /// Returns an error message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns stacktrace of this [`MediaStateTransitionException`].
    #[must_use]
    pub fn trace(&self) -> String {
        self.trace.to_string()
    }

    /// Returns concrete error kind of this [`MediaStateTransitionException`].
    // false positive: destructors cannot be evaluated at compile-time
    #[allow(clippy::missing_const_for_fn)]
    #[must_use]
    pub fn kind(&self) -> MediaStateTransitionExceptionKind {
        self.kind
    }
}

/// Errors occurring in [`RoomHandle::set_local_media_settings()`][1] method.
///
/// [1]: crate::api::RoomHandle::set_local_media_settings
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
#[derive(Debug)]
pub struct MediaSettingsUpdateException {
    /// Error message describing the problem.
    message: Cow<'static, str>,

    /// Original [`room::ChangeMediaStateError`] that was encountered while
    /// updating local media settings.
    cause: Traced<room::ChangeMediaStateError>,

    /// Whether media settings were successfully rolled back after new settings
    /// application failed.
    rolled_back: bool,
}

impl MediaSettingsUpdateException {
    /// Creates a new [`MediaSettingsUpdateException`] from the provided error
    /// `message`, `cause` and `rolled_back` property.
    #[must_use]
    pub fn new<T: Into<Cow<'static, str>>>(
        message: T,
        cause: Traced<room::ChangeMediaStateError>,
        rolled_back: bool,
    ) -> Self {
        Self {
            message: message.into(),
            rolled_back,
            cause,
        }
    }
}

#[cfg_attr(target_family = "wasm", allow(clippy::unused_unit))]
#[cfg_attr(target_family = "wasm", wasm_bindgen)]
impl MediaSettingsUpdateException {
    /// Returns an error message describing the problem.
    #[must_use]
    pub fn message(&self) -> String {
        self.message.to_string()
    }

    /// Returns the original [`room::ChangeMediaStateError`] that was
    /// encountered while updating local media settings.
    #[must_use]
    pub fn cause(&self) -> Error {
        self.cause.clone().into()
    }

    /// Returns whether media settings were successfully rolled back after new
    /// settings application failed.
    // false positive: destructors cannot be evaluated at compile-time
    #[allow(clippy::missing_const_for_fn)]
    #[must_use]
    pub fn rolled_back(&self) -> bool {
        self.rolled_back
    }
}

impl From<Traced<media::HandleDetachedError>> for Error {
    fn from(err: Traced<media::HandleDetachedError>) -> Self {
        let (err, trace) = err.split();
        StateError::new(err.to_string(), trace).into()
    }
}

impl From<Traced<connection::HandleDetachedError>> for Error {
    fn from(err: Traced<connection::HandleDetachedError>) -> Self {
        let (err, trace) = err.split();
        StateError::new(err.to_string(), trace).into()
    }
}

impl From<Traced<room::HandleDetachedError>> for Error {
    fn from(err: Traced<room::HandleDetachedError>) -> Self {
        let (err, trace) = err.split();
        StateError::new(err.to_string(), trace).into()
    }
}

impl From<Traced<EnumerateDevicesError>> for Error {
    fn from(err: Traced<EnumerateDevicesError>) -> Self {
        let (err, stacktrace) = err.split();
        match err {
            EnumerateDevicesError::Failed(err) => {
                EnumerateDevicesException::new(err, stacktrace).into()
            }
            EnumerateDevicesError::Detached => {
                StateError::new(err.to_string(), stacktrace).into()
            }
        }
    }
}

impl From<Traced<EnumerateDisplaysError>> for Error {
    fn from(err: Traced<EnumerateDisplaysError>) -> Self {
        let (err, stacktrace) = err.split();
        match err {
            EnumerateDisplaysError::Failed(err) => {
                InternalException::new(err.to_string(), Some(err), stacktrace)
                    .into()
            }
            EnumerateDisplaysError::Detached => {
                StateError::new(err.to_string(), stacktrace).into()
            }
        }
    }
}

impl From<Traced<InvalidOutputAudioDeviceIdError>> for Error {
    fn from(err: Traced<InvalidOutputAudioDeviceIdError>) -> Self {
        let (_, trace) = err.split();
        InvalidOutputAudioDeviceIdException::new(trace).into()
    }
}

impl From<Traced<MicVolumeError>> for Error {
    fn from(err: Traced<MicVolumeError>) -> Self {
        let (err, stacktrace) = err.split();
        match err {
            MicVolumeError::MicVolumeError(err) => {
                MicVolumeException::new(err, stacktrace).into()
            }
            MicVolumeError::Detached => {
                StateError::new(err.to_string(), stacktrace).into()
            }
        }
    }
}

impl From<Traced<InitLocalTracksError>> for Error {
    fn from(err: Traced<InitLocalTracksError>) -> Self {
        use GetDisplayMediaError as Gdm;
        use GetUserMediaError as Gum;
        use InitLocalTracksError as Err;
        use LocalMediaInitExceptionKind as Kind;

        let (err, stacktrace) = err.split();
        let message = err.to_string();

        let (kind, cause) = match err {
            Err::Detached => {
                return StateError::new(message, stacktrace).into()
            }
            Err::GetUserMediaFailed(Gum::PlatformRequestFailed(
                platform::GetUserMediaError::Audio(cause),
            )) => (Kind::GetUserMediaAudioFailed, Some(cause)),
            Err::GetUserMediaFailed(Gum::PlatformRequestFailed(
                platform::GetUserMediaError::Video(cause),
            )) => (Kind::GetUserMediaVideoFailed, Some(cause)),
            Err::GetUserMediaFailed(Gum::PlatformRequestFailed(
                platform::GetUserMediaError::Unknown(cause),
            )) => (Kind::GetUserMediaFailed, Some(cause)),
            Err::GetDisplayMediaFailed(Gdm::PlatformRequestFailed(cause)) => {
                (Kind::GetDisplayMediaFailed, Some(cause))
            }
            Err::GetUserMediaFailed(Gum::LocalTrackIsEnded(_))
            | Err::GetDisplayMediaFailed(Gdm::LocalTrackIsEnded(_)) => {
                (Kind::LocalTrackIsEnded, None)
            }
        };

        LocalMediaInitException::new(kind, message, cause, stacktrace).into()
    }
}

impl From<Traced<ReconnectError>> for Error {
    fn from(err: Traced<ReconnectError>) -> Self {
        let (err, trace) = err.split();

        match err {
            ReconnectError::Detached => {
                StateError::new(err.to_string(), trace).into()
            }
            ReconnectError::Session(err) => Traced::compose(err, trace).into(),
        }
    }
}

impl From<Traced<SessionError>> for Error {
    fn from(err: Traced<SessionError>) -> Self {
        use ConnectionLostReason as Reason;
        use RpcClientExceptionKind as Kind;
        use SessionError as SE;

        let (err, trace) = err.split();
        let message = err.to_string();

        let mut cause = None;
        let kind = match err {
            SE::SessionFinished(_) => Some(Kind::SessionFinished),
            SE::NoCredentials
            | SE::SessionUnexpectedlyDropped
            | SE::NewConnectionInfo => None,
            SE::RpcClient(e) => {
                cause = e.cause();
                None
            }
            SE::AuthorizationFailed => Some(Kind::AuthorizationFailed),
            SE::ConnectionLost(reason) => {
                if let Reason::ConnectError(e) = reason {
                    cause = e.into_inner().cause();
                };
                Some(Kind::ConnectionLost)
            }
        };

        if let Some(rpc_kind) = kind {
            RpcClientException::new(rpc_kind, message, cause, trace).into()
        } else {
            InternalException::new(message, cause, trace).into()
        }
    }
}

impl From<Traced<room::RoomJoinError>> for Error {
    fn from(err: Traced<room::RoomJoinError>) -> Self {
        let (err, trace) = err.split();
        let message = err.to_string();

        match err {
            room::RoomJoinError::Detached
            | room::RoomJoinError::CallbackNotSet(_) => {
                StateError::new(message, trace).into()
            }
            room::RoomJoinError::ConnectionInfoParse(_) => {
                FormatException::new(message).into()
            }
            room::RoomJoinError::SessionError(err) => {
                Traced::compose(err, trace).into()
            }
        }
    }
}

impl From<Traced<connection::ChangeMediaStateError>> for Error {
    fn from(err: Traced<connection::ChangeMediaStateError>) -> Self {
        let (err, trace) = err.split();
        let message = err.to_string();

        match err {
            connection::ChangeMediaStateError::Detached => {
                StateError::new(err.to_string(), trace).into()
            }
            connection::ChangeMediaStateError::ProhibitedState(_) => {
                MediaStateTransitionException::new(
                    message,
                    trace,
                    MediaStateTransitionExceptionKind::ProhibitedState,
                )
                .into()
            }
            connection::ChangeMediaStateError::TransitionIntoOppositeState(
                _,
            ) => MediaStateTransitionException::new(
                message,
                trace,
                MediaStateTransitionExceptionKind::OppositeState,
            )
            .into(),
        }
    }
}

impl From<Traced<room::ChangeMediaStateError>> for Error {
    fn from(err: Traced<room::ChangeMediaStateError>) -> Self {
        let (err, trace) = err.split();
        let message = err.to_string();

        match err {
            room::ChangeMediaStateError::Detached => {
                StateError::new(err.to_string(), trace).into()
            }
            room::ChangeMediaStateError::CouldNotGetLocalMedia(err) => {
                Traced::compose(err, trace).into()
            }
            room::ChangeMediaStateError::ProhibitedState(_) => {
                MediaStateTransitionException::new(
                    message,
                    trace,
                    MediaStateTransitionExceptionKind::ProhibitedState,
                )
                .into()
            }
            room::ChangeMediaStateError::TransitionIntoOppositeState(_) => {
                MediaStateTransitionException::new(
                    message,
                    trace,
                    MediaStateTransitionExceptionKind::OppositeState,
                )
                .into()
            }
            room::ChangeMediaStateError::InvalidLocalTracks(_)
            | room::ChangeMediaStateError::InsertLocalTracksError(_) => {
                InternalException::new(message, None, trace).into()
            }
        }
    }
}

impl From<room::ConstraintsUpdateError> for Error {
    fn from(err: room::ConstraintsUpdateError) -> Self {
        let message = err.to_string();

        let (err, rolled_back) = match err {
            room::ConstraintsUpdateError::Recovered(err) => (err, true),
            room::ConstraintsUpdateError::RecoverFailed {
                recover_reason,
                ..
            } => (recover_reason, false),
            room::ConstraintsUpdateError::Errored(err) => (err, false),
        };

        MediaSettingsUpdateException::new(message, err, rolled_back).into()
    }
}

impl From<Traced<LocalMediaError>> for Error {
    fn from(err: Traced<LocalMediaError>) -> Self {
        use InsertLocalTracksError as IE;
        use LocalMediaError as ME;
        use UpdateLocalStreamError as UE;

        let (err, trace) = err.split();
        let message = err.to_string();

        match err {
            ME::UpdateLocalStreamError(err) => match err {
                UE::CouldNotGetLocalMedia(err) => {
                    Traced::compose(err, trace).into()
                }
                UE::InvalidLocalTracks(_)
                | UE::InsertLocalTracksError(
                    IE::InvalidMediaTrack | IE::NotEnoughTracks,
                ) => InternalException::new(message, None, trace).into(),
                UE::InsertLocalTracksError(IE::CouldNotInsertLocalTrack(_)) => {
                    InternalException::new(message, None, trace).into()
                }
            },
            ME::SenderCreateError(CreateError::TransceiverNotFound(_)) => {
                InternalException::new(message, None, trace).into()
            }
            ME::SenderCreateError(CreateError::CannotDisableRequiredSender) => {
                MediaStateTransitionException::new(
                    message,
                    trace,
                    MediaStateTransitionExceptionKind::ProhibitedState,
                )
                .into()
            }
        }
    }
}