Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. use std::error::Error;
  2. use std::fmt;
  3. use std::fmt::Display;
  4. use std::io::Write;
  5.  
  6. #[derive(Debug)]
  7. pub struct BasicError {
  8. message: String,
  9. }
  10.  
  11. impl BasicError {
  12. pub fn new(message: String) -> Self {
  13. Self { message }
  14. }
  15. }
  16.  
  17. //impl Error for BasicError {
  18. // fn description(&self) -> &str {
  19. // &self.message
  20. // }
  21. //}
  22.  
  23. impl Display for BasicError {
  24. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  25. write!(f, "{}", self.message)
  26. }
  27. }
  28.  
  29. impl From<Box<dyn Error>> for BasicError {
  30. fn from(err: Box<dyn Error>) -> Self {
  31. Self::new(err.description().to_string())
  32. }
  33. }
  34.  
  35. impl From<&str> for BasicError {
  36. fn from(value: &str) -> Self {
  37. Self::new(value.to_string())
  38. }
  39. }
  40.  
  41. impl From<String> for BasicError {
  42. fn from(value: String) -> Self {
  43. Self::new(value)
  44. }
  45. }
  46.  
  47. #[derive(PartialEq)]
  48. pub enum Environment {
  49. Development,
  50. Staging,
  51. Production,
  52. }
  53.  
  54. pub struct AppEnv {
  55. pub environment: Environment,
  56. pub base_url: String,
  57. }
  58.  
  59. impl AppEnv {
  60. pub fn from_std_env() -> Result<AppEnv, Box<BasicError>> {
  61. const ENVIRONMENT_KEY: &'static str = "ENVIRONMENT";
  62. const BASE_URL_KEY: &'static str = "BASE_URL";
  63.  
  64. let environment_str = std::env::var(ENVIRONMENT_KEY)?;
  65. let base_url = std::env::var(BASE_URL_KEY)?;
  66.  
  67. let environment = match environment_str.as_ref() {
  68. "DEVELOPMENT" => Ok(Environment::Development),
  69. "STAGING" => Ok(Environment::Staging),
  70. "PRODUCTION" => Ok(Environment::Production),
  71. key => Err(format!(
  72. "Unable to parse environment variable '{} -> {}'",
  73. ENVIRONMENT_KEY, environment_str
  74. )),
  75. }?;
  76.  
  77. Ok(AppEnv {
  78. base_url,
  79. environment,
  80. })
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement