libp2p_webrtc_websys/
error.rs

1use wasm_bindgen::{JsCast, JsValue};
2
3/// Errors that may happen on the [`Transport`](crate::Transport) or the
4/// [`Connection`](crate::Connection).
5#[derive(thiserror::Error, Debug)]
6pub enum Error {
7    #[error("Invalid multiaddr: {0}")]
8    InvalidMultiaddr(&'static str),
9
10    #[error("JavaScript error: {0}")]
11    Js(String),
12
13    #[error("JavaScript typecasting failed")]
14    JsCastFailed,
15
16    #[error("Unknown remote peer ID")]
17    UnknownRemotePeerId,
18
19    #[error("Connection error: {0}")]
20    Connection(String),
21
22    #[error("Authentication error")]
23    Authentication(#[from] AuthenticationError),
24}
25
26/// New-type wrapper to hide `libp2p_noise` from the public API.
27#[derive(thiserror::Error, Debug)]
28#[error(transparent)]
29pub struct AuthenticationError(pub(crate) libp2p_webrtc_utils::noise::Error);
30
31impl Error {
32    pub(crate) fn from_js_value(value: JsValue) -> Self {
33        let s = if value.is_instance_of::<js_sys::Error>() {
34            js_sys::Error::from(value)
35                .to_string()
36                .as_string()
37                .unwrap_or_else(|| "Unknown error".to_string())
38        } else {
39            "Unknown error".to_string()
40        };
41
42        Error::Js(s)
43    }
44}
45
46impl From<JsValue> for Error {
47    fn from(value: JsValue) -> Self {
48        Error::from_js_value(value)
49    }
50}
51
52impl From<String> for Error {
53    fn from(value: String) -> Self {
54        Error::Js(value)
55    }
56}
57
58impl From<std::io::Error> for Error {
59    fn from(value: std::io::Error) -> Self {
60        Error::Js(value.to_string())
61    }
62}