1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //! Errors that may occur in this crate.
15 //!
16 //! This module provide unified encapsulation of HTTP errors.
17 //!
18 //! [`HttpError`] encapsulates error information related to all http protocols
19 //! including `UriError`, `H1Error`, etc.
20 //!
21 //! [`HttpError`]: HttpError
22 
23 use core::fmt::{Debug, Display, Formatter};
24 use std::convert::Infallible;
25 use std::error::Error;
26 
27 #[cfg(feature = "http1_1")]
28 use crate::h1::H1Error;
29 #[cfg(feature = "http2")]
30 use crate::h2::H2Error;
31 use crate::request::uri::InvalidUri;
32 
33 /// Errors that may occur when using this crate.
34 #[derive(Debug, Eq, PartialEq)]
35 pub struct HttpError {
36     kind: ErrorKind,
37 }
38 
39 impl From<ErrorKind> for HttpError {
from(kind: ErrorKind) -> Self40     fn from(kind: ErrorKind) -> Self {
41         HttpError { kind }
42     }
43 }
44 
45 impl From<InvalidUri> for HttpError {
from(err: InvalidUri) -> Self46     fn from(err: InvalidUri) -> Self {
47         ErrorKind::Uri(err).into()
48     }
49 }
50 
51 #[cfg(feature = "http2")]
52 impl From<H2Error> for HttpError {
from(err: H2Error) -> Self53     fn from(err: H2Error) -> Self {
54         ErrorKind::H2(err).into()
55     }
56 }
57 
58 impl From<Infallible> for HttpError {
from(_value: Infallible) -> Self59     fn from(_value: Infallible) -> Self {
60         unreachable!()
61     }
62 }
63 
64 impl Display for HttpError {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result65     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
66         Debug::fmt(self, f)
67     }
68 }
69 
70 impl Error for HttpError {}
71 
72 #[derive(Debug, Eq, PartialEq)]
73 pub(crate) enum ErrorKind {
74     /// An invalid input parameter was passed to a method of this crate.
75     InvalidInput,
76 
77     /// Errors related to URIs.
78     Uri(InvalidUri),
79 
80     /// Errors related to `HTTP/1`.
81     #[cfg(feature = "http1_1")]
82     H1(H1Error),
83 
84     /// Errors related to `HTTP/2`.
85     #[cfg(feature = "http2")]
86     H2(H2Error),
87 }
88