[go: up one dir, main page]

mockito/
error.rs

1use std::error::Error as ErrorTrait;
2use std::fmt::Display;
3
4///
5/// Contains information about an error occurence
6///
7#[derive(Debug)]
8pub struct Error {
9    /// The type of this error
10    pub kind: ErrorKind,
11    /// Some errors come with more context
12    pub context: Option<String>,
13}
14
15impl Error {
16    pub(crate) fn new(kind: ErrorKind) -> Error {
17        Error {
18            kind,
19            context: None,
20        }
21    }
22
23    pub(crate) fn new_with_context(kind: ErrorKind, context: impl Display) -> Error {
24        Error {
25            kind,
26            context: Some(context.to_string()),
27        }
28    }
29}
30
31impl Display for Error {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        write!(
34            f,
35            "{} (context: {})",
36            self.kind.description(),
37            self.context.as_ref().unwrap_or(&"none".to_string())
38        )
39    }
40}
41
42impl ErrorTrait for Error {}
43
44///
45/// The type of an error
46///
47#[derive(Debug)]
48pub enum ErrorKind {
49    /// The server is not running
50    ServerFailure,
51    /// The server is busy
52    ServerBusy,
53    /// A lock can't be bypassed
54    Deadlock,
55    /// Could not deliver a response
56    ResponseFailure,
57    /// The status code is invalid or out of range
58    InvalidStatusCode,
59    /// Failed to read the request body
60    RequestBodyFailure,
61    /// Failed to write the response body
62    ResponseBodyFailure,
63    /// File not found
64    FileNotFound,
65    /// Invalid header name
66    InvalidHeaderName,
67}
68
69impl ErrorKind {
70    fn description(&self) -> &'static str {
71        match self {
72            ErrorKind::ServerFailure => "the server is not running",
73            ErrorKind::ServerBusy => "the server is busy",
74            ErrorKind::Deadlock => "a lock can't be bypassed",
75            ErrorKind::ResponseFailure => "could not deliver a response",
76            ErrorKind::InvalidStatusCode => "invalid status code",
77            ErrorKind::RequestBodyFailure => "failed to read the request body",
78            ErrorKind::ResponseBodyFailure => "failed to write the response body",
79            ErrorKind::FileNotFound => "file not found",
80            ErrorKind::InvalidHeaderName => "invalid header name",
81        }
82    }
83}