Skip to main content

brokaw/
error.rs

1use std::str::Utf8Error;
2
3use crate::types::prelude::*;
4
5/// All of the ways that a failure can occur within Brokaw
6#[derive(Debug, thiserror::Error)]
7pub enum Error {
8    /// This error indicates an application layer failure.
9    ///
10    /// For example, asking for a non-existent group will return
11    /// [`NoSuchNewsGroup`](`crate::types::prelude::Kind::NoSuchNewsgroup`) (code 411),
12    /// which is not a protocol error.
13    #[error("Server returned {code:?} -- {msg:?}")]
14    Failure {
15        /// The response code
16        code: ResponseCode,
17        /// The raw response
18        resp: RawResponse,
19        /// An error message associated with the response
20        msg: Option<String>,
21    },
22    #[error(transparent)]
23    /// An error raised by the underlying connection
24    ///
25    /// This is usually of an I/O error or a TLS error
26    Connection(#[from] crate::raw::error::Error),
27    /// An error deserializing a [RawResponse] into a concrete type
28    #[error("{0}")]
29    Deserialization(String),
30    /// An error deserializing bytes as UTF-8
31    #[error("{0}")]
32    Utf8(#[from] Utf8Error),
33}
34
35impl Error {
36    pub(crate) fn failure(resp: RawResponse) -> Self {
37        Error::Failure {
38            code: resp.code(),
39            resp,
40            msg: None,
41        }
42    }
43
44    pub(crate) fn de(msg: impl AsRef<str>) -> Self {
45        Error::Deserialization(msg.as_ref().to_string())
46    }
47
48    pub(crate) fn missing_field(name: impl AsRef<str>) -> Self {
49        Error::Deserialization(format!("Missing field `{}`", name.as_ref()))
50    }
51
52    pub(crate) fn parse_error(name: impl AsRef<str>) -> Self {
53        Error::Deserialization(format!("Could not parse field `{}`", name.as_ref()))
54    }
55
56    pub(crate) fn missing_data_blocks() -> Self {
57        Error::Deserialization("Response is missing multi-line data blocks".to_string())
58    }
59
60    pub(crate) fn invalid_data_blocks(msg: impl AsRef<str>) -> Self {
61        Error::Deserialization(format!("Invalid data-block section -- {}", msg.as_ref()))
62    }
63}
64
65/// A result type returned by the library
66pub type Result<T> = std::result::Result<T, Error>;