Advertisement
Guest User

Untitled

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