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 libp2p_core::Multiaddr;
22use crate::tls;
23use std::{error, fmt};
24
25/// Error in WebSockets.
26#[derive(Debug)]
27pub enum Error<E> {
28 /// Error in the transport layer underneath.
29 Transport(E),
30 /// A TLS related error.
31 Tls(tls::Error),
32 /// Websocket handshake error.
33 Handshake(Box<dyn error::Error + Send + Sync>),
34 /// The configured maximum of redirects have been made.
35 TooManyRedirects,
36 /// A multi-address is not supported.
37 InvalidMultiaddr(Multiaddr),
38 /// The location header URL was invalid.
39 InvalidRedirectLocation,
40 /// Websocket base framing error.
41 Base(Box<dyn error::Error + Send + Sync>)
42}
43
44impl<E: fmt::Display> fmt::Display for Error<E> {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 Error::Transport(err) => write!(f, "{}", err),
48 Error::Tls(err) => write!(f, "{}", err),
49 Error::Handshake(err) => write!(f, "{}", err),
50 Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {}", ma),
51 Error::TooManyRedirects => f.write_str("too many redirects"),
52 Error::InvalidRedirectLocation => f.write_str("invalid redirect location"),
53 Error::Base(err) => write!(f, "{}", err)
54 }
55 }
56}
57
58impl<E: error::Error + 'static> error::Error for Error<E> {
59 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
60 match self {
61 Error::Transport(err) => Some(err),
62 Error::Tls(err) => Some(err),
63 Error::Handshake(err) => Some(&**err),
64 Error::Base(err) => Some(&**err),
65 Error::InvalidMultiaddr(_)
66 | Error::TooManyRedirects
67 | Error::InvalidRedirectLocation => None
68 }
69 }
70}
71
72impl<E> From<tls::Error> for Error<E> {
73 fn from(e: tls::Error) -> Self {
74 Error::Tls(e)
75 }
76}