grid_sdk/error/invalid_argument.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 InvalidArgumentError implementation.
16
17use std::error;
18use std::fmt;
19
20/// An error returned when an argument passed to a function does not conform to the expected format.
21///
22/// This always indicates a programming error on behalf of the caller, since the caller should have
23/// verified the argument prior to passing it into the function.
24#[derive(Debug)]
25pub struct InvalidArgumentError {
26 argument: String,
27 message: String,
28}
29
30impl InvalidArgumentError {
31 /// Constructs a new `InvalidArgumentError` with a specified argument and message string.
32 ///
33 /// The argument passed in should be the name of the argument in the function's signature. The
34 /// message should be the reason it is invalid, and should not contain the name of the argument
35 /// (since Display will combine both argument and message).
36 ///
37 /// The implementation of `std::fmt::Display` for this error will be a combination of the
38 /// argument and the message string provided.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// use grid_sdk::error::InvalidArgumentError;
44 ///
45 /// let invalid_arg_error = InvalidArgumentError::new("arg1".to_string(), "argument too long".to_string());
46 /// assert_eq!(format!("{}", invalid_arg_error), "argument too long (arg1)");
47 /// ```
48 pub fn new(argument: String, message: String) -> Self {
49 Self { argument, message }
50 }
51
52 /// Returns the name of the invalid argument.
53 pub fn argument(&self) -> String {
54 self.argument.clone()
55 }
56
57 /// Returns the message, which is an explanation of why the argument is invalid.
58 pub fn message(&self) -> String {
59 self.message.clone()
60 }
61}
62
63impl error::Error for InvalidArgumentError {}
64
65impl fmt::Display for InvalidArgumentError {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67 write!(f, "{} ({})", &self.message, &self.argument)
68 }
69}
70
71#[cfg(test)]
72pub mod tests {
73 use super::*;
74
75 /// Tests that error constructed with `InvalidArgumentError::new` return message as the
76 /// display string.
77 #[test]
78 fn test_display() {
79 let arg = "arg1";
80 let msg = "test message";
81 let err = InvalidArgumentError::new(arg.to_string(), msg.to_string());
82 assert_eq!(format!("{}", err), format!("{} ({})", msg, arg));
83 }
84}