error.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //
  2. // Error generator macro
  3. //
  4. use std::error::Error as StdError;
  5. macro_rules! make_error {
  6. ( $( $name:ident ( $ty:ty ): $src_fn:expr, $usr_msg_fun:expr ),+ $(,)? ) => {
  7. const BAD_REQUEST: u16 = 400;
  8. pub enum ErrorKind { $($name( $ty )),+ }
  9. pub struct Error { message: String, error: ErrorKind, error_code: u16 }
  10. $(impl From<$ty> for Error {
  11. fn from(err: $ty) -> Self { Error::from((stringify!($name), err)) }
  12. })+
  13. $(impl<S: Into<String>> From<(S, $ty)> for Error {
  14. fn from(val: (S, $ty)) -> Self {
  15. Error { message: val.0.into(), error: ErrorKind::$name(val.1), error_code: BAD_REQUEST }
  16. }
  17. })+
  18. impl StdError for Error {
  19. fn source(&self) -> Option<&(dyn StdError + 'static)> {
  20. match &self.error {$( ErrorKind::$name(e) => $src_fn(e), )+}
  21. }
  22. }
  23. impl std::fmt::Display for Error {
  24. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  25. match &self.error {$(
  26. ErrorKind::$name(e) => f.write_str(&$usr_msg_fun(e, &self.message)),
  27. )+}
  28. }
  29. }
  30. };
  31. }
  32. use diesel::result::Error as DieselErr;
  33. use diesel::ConnectionError as DieselConErr;
  34. use diesel_migrations::RunMigrationsError as DieselMigErr;
  35. use diesel::r2d2::PoolError as R2d2Err;
  36. use handlebars::RenderError as HbErr;
  37. use jsonwebtoken::errors::Error as JWTErr;
  38. use regex::Error as RegexErr;
  39. use reqwest::Error as ReqErr;
  40. use serde_json::{Error as SerdeErr, Value};
  41. use std::io::Error as IOErr;
  42. use std::time::SystemTimeError as TimeErr;
  43. use u2f::u2ferror::U2fError as U2fErr;
  44. use yubico::yubicoerror::YubicoError as YubiErr;
  45. use lettre::address::AddressError as AddrErr;
  46. use lettre::error::Error as LettreErr;
  47. use lettre::message::mime::FromStrError as FromStrErr;
  48. use lettre::transport::smtp::Error as SmtpErr;
  49. #[derive(Serialize)]
  50. pub struct Empty {}
  51. // Error struct
  52. // Contains a String error message, meant for the user and an enum variant, with an error of different types.
  53. //
  54. // After the variant itself, there are two expressions. The first one indicates whether the error contains a source error (that we pretty print).
  55. // The second one contains the function used to obtain the response sent to the client
  56. make_error! {
  57. // Just an empty error
  58. EmptyError(Empty): _no_source, _serialize,
  59. // Used to represent err! calls
  60. SimpleError(String): _no_source, _api_error,
  61. // Used for special return values, like 2FA errors
  62. JsonError(Value): _no_source, _serialize,
  63. DbError(DieselErr): _has_source, _api_error,
  64. R2d2Error(R2d2Err): _has_source, _api_error,
  65. U2fError(U2fErr): _has_source, _api_error,
  66. SerdeError(SerdeErr): _has_source, _api_error,
  67. JWTError(JWTErr): _has_source, _api_error,
  68. TemplError(HbErr): _has_source, _api_error,
  69. //WsError(ws::Error): _has_source, _api_error,
  70. IOError(IOErr): _has_source, _api_error,
  71. TimeError(TimeErr): _has_source, _api_error,
  72. ReqError(ReqErr): _has_source, _api_error,
  73. RegexError(RegexErr): _has_source, _api_error,
  74. YubiError(YubiErr): _has_source, _api_error,
  75. LettreError(LettreErr): _has_source, _api_error,
  76. AddressError(AddrErr): _has_source, _api_error,
  77. SmtpError(SmtpErr): _has_source, _api_error,
  78. FromStrError(FromStrErr): _has_source, _api_error,
  79. DieselConError(DieselConErr): _has_source, _api_error,
  80. DieselMigError(DieselMigErr): _has_source, _api_error,
  81. }
  82. impl std::fmt::Debug for Error {
  83. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  84. match self.source() {
  85. Some(e) => write!(f, "{}.\n[CAUSE] {:#?}", self.message, e),
  86. None => match self.error {
  87. ErrorKind::EmptyError(_) => Ok(()),
  88. ErrorKind::SimpleError(ref s) => {
  89. if &self.message == s {
  90. write!(f, "{}", self.message)
  91. } else {
  92. write!(f, "{}. {}", self.message, s)
  93. }
  94. }
  95. ErrorKind::JsonError(_) => write!(f, "{}", self.message),
  96. _ => unreachable!(),
  97. },
  98. }
  99. }
  100. }
  101. impl Error {
  102. pub fn new<M: Into<String>, N: Into<String>>(usr_msg: M, log_msg: N) -> Self {
  103. (usr_msg, log_msg.into()).into()
  104. }
  105. pub fn empty() -> Self {
  106. Empty {}.into()
  107. }
  108. pub fn with_msg<M: Into<String>>(mut self, msg: M) -> Self {
  109. self.message = msg.into();
  110. self
  111. }
  112. pub const fn with_code(mut self, code: u16) -> Self {
  113. self.error_code = code;
  114. self
  115. }
  116. }
  117. pub trait MapResult<S> {
  118. fn map_res(self, msg: &str) -> Result<S, Error>;
  119. }
  120. impl<S, E: Into<Error>> MapResult<S> for Result<S, E> {
  121. fn map_res(self, msg: &str) -> Result<S, Error> {
  122. self.map_err(|e| e.into().with_msg(msg))
  123. }
  124. }
  125. impl<E: Into<Error>> MapResult<()> for Result<usize, E> {
  126. fn map_res(self, msg: &str) -> Result<(), Error> {
  127. self.and(Ok(())).map_res(msg)
  128. }
  129. }
  130. impl<S> MapResult<S> for Option<S> {
  131. fn map_res(self, msg: &str) -> Result<S, Error> {
  132. self.ok_or_else(|| Error::new(msg, ""))
  133. }
  134. }
  135. const fn _has_source<T>(e: T) -> Option<T> {
  136. Some(e)
  137. }
  138. fn _no_source<T, S>(_: T) -> Option<S> {
  139. None
  140. }
  141. fn _serialize(e: &impl serde::Serialize, _msg: &str) -> String {
  142. serde_json::to_string(e).unwrap()
  143. }
  144. fn _api_error(_: &impl std::any::Any, msg: &str) -> String {
  145. let json = json!({
  146. "Message": "",
  147. "error": "",
  148. "error_description": "",
  149. "ValidationErrors": {"": [ msg ]},
  150. "ErrorModel": {
  151. "Message": msg,
  152. "Object": "error"
  153. },
  154. "Object": "error"
  155. });
  156. _serialize(&json, "")
  157. }
  158. //
  159. // Rocket responder impl
  160. //
  161. use std::io::Cursor;
  162. use rocket::http::{ContentType, Status};
  163. use rocket::request::Request;
  164. use rocket::response::{self, Responder, Response};
  165. impl<'r> Responder<'r> for Error {
  166. fn respond_to(self, _: &Request) -> response::Result<'r> {
  167. match self.error {
  168. ErrorKind::EmptyError(_) => {} // Don't print the error in this situation
  169. ErrorKind::SimpleError(_) => {} // Don't print the error in this situation
  170. _ => error!(target: "error", "{:#?}", self),
  171. };
  172. let code = Status::from_code(self.error_code).unwrap_or(Status::BadRequest);
  173. Response::build()
  174. .status(code)
  175. .header(ContentType::JSON)
  176. .sized_body(Cursor::new(format!("{}", self)))
  177. .ok()
  178. }
  179. }
  180. //
  181. // Error return macros
  182. //
  183. #[macro_export]
  184. macro_rules! err {
  185. ($msg:expr) => {{
  186. error!("{}", $msg);
  187. return Err(crate::error::Error::new($msg, $msg));
  188. }};
  189. ($usr_msg:expr, $log_value:expr) => {{
  190. error!("{}. {}", $usr_msg, $log_value);
  191. return Err(crate::error::Error::new($usr_msg, $log_value));
  192. }};
  193. }
  194. #[macro_export]
  195. macro_rules! err_discard {
  196. ($msg:expr, $data:expr) => {{
  197. std::io::copy(&mut $data.open(), &mut std::io::sink()).ok();
  198. return Err(crate::error::Error::new($msg, $msg));
  199. }};
  200. ($usr_msg:expr, $log_value:expr, $data:expr) => {{
  201. std::io::copy(&mut $data.open(), &mut std::io::sink()).ok();
  202. return Err(crate::error::Error::new($usr_msg, $log_value));
  203. }};
  204. }
  205. #[macro_export]
  206. macro_rules! err_json {
  207. ($expr:expr, $log_value:expr) => {{
  208. return Err(($log_value, $expr).into());
  209. }};
  210. }
  211. #[macro_export]
  212. macro_rules! err_handler {
  213. ($expr:expr) => {{
  214. error!(target: "auth", "Unauthorized Error: {}", $expr);
  215. return ::rocket::request::Outcome::Failure((rocket::http::Status::Unauthorized, $expr));
  216. }};
  217. ($usr_msg:expr, $log_value:expr) => {{
  218. error!(target: "auth", "Unauthorized Error: {}. {}", $usr_msg, $log_value);
  219. return ::rocket::request::Outcome::Failure((rocket::http::Status::Unauthorized, $usr_msg));
  220. }};
  221. }