rust_nickname_generater/
error.rs

1use new_string_template::error::TemplateError;
2use std::{fmt, num::TryFromIntError};
3
4pub type Result<T> = std::result::Result<T, Error>;
5
6// Define our error types. These may be customized for our error handling cases.
7// Now we will be able to write our own errors, defer to an underlying error
8// implementation, or do something in between.
9#[derive(Debug, PartialEq, Eq)]
10pub enum Error {
11    LengthLimit,
12    NoValidName,
13    StringTemplate(String),
14    UsernameLenConversionFailed(String),
15}
16
17// Generation of an error is completely separate from how it is displayed.
18// There's no need to be concerned about cluttering complex logic with the display style.
19//
20// Note that we don't store any extra info about the errors. This means we can't state
21// which string failed to parse without modifying our types to carry that information.
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24        match self {
25            Self::LengthLimit => f.write_str("The length limit cannot be smaller than the input username"),
26            Self::NoValidName => f.write_str("There are no templates that can fit in the character limit using specified username"),
27            Self::StringTemplate(inner) => f.write_str(inner.to_string().as_str()),
28            Self::UsernameLenConversionFailed(inner) => f.write_str(format!("Failed to convert username.len() into a u32 for comparison. Reason: {}", inner).as_str()),
29        }
30    }
31}
32
33impl From<TemplateError> for Error {
34    fn from(e: TemplateError) -> Self {
35        Self::StringTemplate(format!("{}", e))
36    }
37}
38
39impl From<TryFromIntError> for Error {
40    fn from(e: TryFromIntError) -> Self {
41        Self::UsernameLenConversionFailed(format!("{}", e))
42    }
43}