cargo_fixture/
error.rs

1//! The library error type.
2
3use std::{fmt, io};
4
5use strum::AsRefStr;
6use thiserror::Error;
7
8/// Convenience `Result` alias.
9pub type Result<T, E = Error> = std::result::Result<T, E>;
10
11/// The library error type.
12#[derive(Error, AsRefStr)]
13pub enum Error {
14    /// RPC communication error.
15    #[error("cargo fixture socket serde error")]
16    RpcSerde(#[source] serde_json::Error),
17
18    /// RPC I/O error.
19    #[error("cargo fixture socket I/O error")]
20    RpcIo(#[source] io::Error),
21
22    /// No `CARGO_FIXTURE_SOCKET` set, occurs when fixture or fixture tests are run without `cargo fixture`.
23    #[error("Could not connect: CARGO_FIXTURE_SOCKET not set; cargo fixture not running?")]
24    RpcNoEnvVar,
25
26    /// RPC communication error.
27    #[error("Unexpected RPC response: {0:?}")]
28    RpcMismatch(crate::rpc_socket::Response),
29
30    /// Connection interrupted prematurely.
31    #[error("cargo fixture socket unexpectedly hung up")]
32    RpcHangup,
33
34    /// Serde error when setting or retrieving K-V store value.
35    #[error("De/serialization error")]
36    Serde(#[from] serde_json::Error),
37
38    /// Invalid key or value while attempting to set environment variable
39    #[error("Invalid key or value while attempting to set environment variable")]
40    InvalidSetEnv,
41
42    /// No value set for key in the K-V store value.
43    #[error("No value set for key `{0}`")]
44    MissingKeyValue(String),
45}
46
47impl Error {
48    /// Returns `Some` if this is a K-V store serde error.
49    pub fn as_serde(&self) -> Option<&serde_json::Error> {
50        if let Self::Serde(err) = self {
51            Some(err)
52        } else {
53            None
54        }
55    }
56}
57
58impl<T> From<Error> for Result<T> {
59    fn from(err: Error) -> Self {
60        Err(err)
61    }
62}
63
64impl fmt::Debug for Error {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        let variant = self.as_ref();
67        write!(f, "{variant}: {self}")
68    }
69}