Skip to main content

couchbase_connstr/
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::fmt::{Display, Formatter};
20use std::{fmt, io};
21
22pub type Result<T> = std::result::Result<T, Error>;
23
24#[derive(Debug, Clone)]
25pub struct Error {
26    pub(crate) kind: ErrorKind,
27}
28
29impl Error {
30    pub fn kind(&self) -> &ErrorKind {
31        &self.kind
32    }
33}
34
35#[derive(Debug)]
36#[non_exhaustive]
37pub enum ErrorKind {
38    Parse(String),
39    InvalidArgument { msg: String, arg: String },
40    Io(io::Error),
41    Resolve(hickory_resolver::ResolveError),
42}
43
44impl Clone for ErrorKind {
45    fn clone(&self) -> Self {
46        match self {
47            ErrorKind::Parse(s) => ErrorKind::Parse(s.clone()),
48            ErrorKind::InvalidArgument { msg, arg } => ErrorKind::InvalidArgument {
49                msg: msg.clone(),
50                arg: arg.clone(),
51            },
52            ErrorKind::Io(e) => Self::Io(io::Error::from(e.kind())),
53            ErrorKind::Resolve(e) => Self::Resolve(e.clone()),
54        }
55    }
56}
57
58impl Display for Error {
59    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
60        Display::fmt(&self.kind, f)
61    }
62}
63
64impl Display for ErrorKind {
65    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
66        match self {
67            ErrorKind::Parse(s) => write!(f, "Parse error: {s}"),
68            ErrorKind::InvalidArgument { msg, arg } => {
69                write!(f, "Invalid argument: {msg} ({arg})")
70            }
71            ErrorKind::Io(e) => write!(f, "IO error: {e}"),
72            ErrorKind::Resolve(e) => write!(f, "Resolve error: {e}"),
73        }
74    }
75}
76
77impl From<io::Error> for Error {
78    fn from(e: io::Error) -> Self {
79        Self {
80            kind: ErrorKind::Io(e),
81        }
82    }
83}
84
85impl From<hickory_resolver::ResolveError> for Error {
86    fn from(e: hickory_resolver::ResolveError) -> Self {
87        Self {
88            kind: ErrorKind::Resolve(e),
89        }
90    }
91}
92
93impl From<ErrorKind> for Error {
94    fn from(kind: ErrorKind) -> Self {
95        Self { kind }
96    }
97}