grid_sdk/error/
invalid_state.rs

1// Copyright 2018-2021 Cargill Incorporated
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Module containing InvalidStateError implementation.
16
17use std::error;
18use std::fmt;
19
20/// An error returned when an operation cannot be completed because the state of the underlying
21/// struct is inconsistent.
22///
23/// This can be caused by a caller when a sequence of functions is called in a way that results in
24/// a state which is inconsistent.
25///
26/// This usually indicates a programming error on behalf of the caller.
27#[derive(Debug)]
28pub struct InvalidStateError {
29    message: String,
30}
31
32impl InvalidStateError {
33    /// Constructs a new `InvalidStateError` with a specified message string.
34    ///
35    /// The implementation of `std::fmt::Display` for this error will be the message string
36    /// provided.
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use grid_sdk::error::InvalidStateError;
42    ///
43    /// let invalid_state_error = InvalidStateError::with_message("oops".to_string());
44    /// assert_eq!(format!("{}", invalid_state_error), "oops");
45    /// ```
46    pub fn with_message(message: String) -> Self {
47        Self { message }
48    }
49}
50
51impl error::Error for InvalidStateError {}
52
53impl fmt::Display for InvalidStateError {
54    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55        write!(f, "{}", &self.message)
56    }
57}
58
59#[cfg(test)]
60pub mod tests {
61    use super::*;
62
63    /// Tests that error constructed with `InvalidStateError::with_message` return message as the
64    /// display string.
65    #[test]
66    fn test_display_with_message() {
67        let msg = "test message";
68        let err = InvalidStateError::with_message(msg.to_string());
69        assert_eq!(format!("{}", err), msg);
70    }
71}