libp2p_core/upgrade/error.rs
1// Copyright 2018 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 std::fmt;
22
23use multistream_select::NegotiationError;
24
25/// Error that can happen when upgrading a connection or substream to use a protocol.
26#[derive(Debug)]
27pub enum UpgradeError<E> {
28 /// Error during the negotiation process.
29 Select(NegotiationError),
30 /// Error during the post-negotiation handshake.
31 Apply(E),
32}
33
34impl<E> UpgradeError<E> {
35 pub fn map_err<F, T>(self, f: F) -> UpgradeError<T>
36 where
37 F: FnOnce(E) -> T,
38 {
39 match self {
40 UpgradeError::Select(e) => UpgradeError::Select(e),
41 UpgradeError::Apply(e) => UpgradeError::Apply(f(e)),
42 }
43 }
44
45 pub fn into_err<T>(self) -> UpgradeError<T>
46 where
47 T: From<E>,
48 {
49 self.map_err(Into::into)
50 }
51}
52
53impl<E> fmt::Display for UpgradeError<E>
54where
55 E: fmt::Display,
56{
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 UpgradeError::Select(_) => write!(f, "Multistream select failed"),
60 UpgradeError::Apply(_) => write!(f, "Handshake failed"),
61 }
62 }
63}
64
65impl<E> std::error::Error for UpgradeError<E>
66where
67 E: std::error::Error + 'static,
68{
69 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
70 match self {
71 UpgradeError::Select(e) => Some(e),
72 UpgradeError::Apply(e) => Some(e),
73 }
74 }
75}
76
77impl<E> From<NegotiationError> for UpgradeError<E> {
78 fn from(e: NegotiationError) -> Self {
79 UpgradeError::Select(e)
80 }
81}