ant_libp2p_websocket/error.rs
1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use ant_libp2p_core as libp2p_core;
22
23use std::{error, fmt};
24
25use libp2p_core::Multiaddr;
26
27use crate::tls;
28
29/// Error in WebSockets.
30#[derive(Debug)]
31pub enum Error<E> {
32 /// Error in the transport layer underneath.
33 Transport(E),
34 /// A TLS related error.
35 Tls(tls::Error),
36 /// Websocket handshake error.
37 Handshake(Box<dyn error::Error + Send + Sync>),
38 /// The configured maximum of redirects have been made.
39 TooManyRedirects,
40 /// A multi-address is not supported.
41 InvalidMultiaddr(Multiaddr),
42 /// The location header URL was invalid.
43 InvalidRedirectLocation,
44 /// Websocket base framing error.
45 Base(Box<dyn error::Error + Send + Sync>),
46}
47
48impl<E: fmt::Display> fmt::Display for Error<E> {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 match self {
51 Error::Transport(err) => write!(f, "{err}"),
52 Error::Tls(err) => write!(f, "{err}"),
53 Error::Handshake(err) => write!(f, "{err}"),
54 Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {ma}"),
55 Error::TooManyRedirects => f.write_str("too many redirects"),
56 Error::InvalidRedirectLocation => f.write_str("invalid redirect location"),
57 Error::Base(err) => write!(f, "{err}"),
58 }
59 }
60}
61
62impl<E: error::Error + 'static> error::Error for Error<E> {
63 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
64 match self {
65 Error::Transport(err) => Some(err),
66 Error::Tls(err) => Some(err),
67 Error::Handshake(err) => Some(&**err),
68 Error::Base(err) => Some(&**err),
69 Error::InvalidMultiaddr(_)
70 | Error::TooManyRedirects
71 | Error::InvalidRedirectLocation => None,
72 }
73 }
74}
75
76impl<E> From<tls::Error> for Error<E> {
77 fn from(e: tls::Error) -> Self {
78 Error::Tls(e)
79 }
80}