couchbase_core/httpx/
error.rs

1/*
2 *
3 *  * Copyright (c) 2025 Couchbase, Inc.
4 *  *
5 *  * Licensed under the Apache License, Version 2.0 (the "License");
6 *  * you may not use this file except in compliance with the License.
7 *  * You may obtain a copy of the License at
8 *  *
9 *  *    http://www.apache.org/licenses/LICENSE-2.0
10 *  *
11 *  * Unless required by applicable law or agreed to in writing, software
12 *  * distributed under the License is distributed on an "AS IS" BASIS,
13 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  * See the License for the specific language governing permissions and
15 *  * limitations under the License.
16 *
17 */
18
19use std::error::Error as StdError;
20use std::fmt::{Display, Formatter};
21
22pub type Result<T> = std::result::Result<T, Error>;
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Error {
26    inner: Box<ErrorImpl>,
27}
28
29impl Display for Error {
30    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31        write!(f, "{}", self.inner.kind)
32    }
33}
34
35impl StdError for Error {}
36
37impl Error {
38    pub(crate) fn new_message_error(msg: impl Into<String>) -> Self {
39        Self {
40            inner: Box::new(ErrorImpl {
41                kind: ErrorKind::Message(msg.into()),
42            }),
43        }
44    }
45
46    pub(crate) fn new_connection_error(msg: impl Into<String>) -> Self {
47        Self {
48            inner: Box::new(ErrorImpl {
49                kind: ErrorKind::Connection { msg: msg.into() },
50            }),
51        }
52    }
53
54    pub(crate) fn new_decoding_error(msg: impl Into<String>) -> Self {
55        Self {
56            inner: Box::new(ErrorImpl {
57                kind: ErrorKind::Decoding(msg.into()),
58            }),
59        }
60    }
61
62    pub fn is_connection_error(&self) -> bool {
63        matches!(self.inner.kind, ErrorKind::Connection { .. })
64    }
65
66    pub fn is_decoding_error(&self) -> bool {
67        matches!(self.inner.kind, ErrorKind::Decoding { .. })
68    }
69
70    pub fn kind(&self) -> &ErrorKind {
71        &self.inner.kind
72    }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ErrorImpl {
77    kind: ErrorKind,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum ErrorKind {
83    #[non_exhaustive]
84    Connection {
85        msg: String,
86    },
87    Decoding(String),
88    Message(String),
89}
90
91impl Display for ErrorKind {
92    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
93        match self {
94            Self::Connection { msg } => write!(f, "connection error {msg}"),
95            Self::Decoding(msg) => write!(f, "decoding error: {msg}"),
96            Self::Message(msg) => write!(f, "{msg}"),
97        }
98    }
99}