error.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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::r2d2::PoolError as R2d2Err;
  33. use diesel::result::Error as DieselErr;
  34. use diesel::ConnectionError as DieselConErr;
  35. use diesel_migrations::RunMigrationsError as DieselMigErr;
  36. use handlebars::RenderError as HbErr;
  37. use jsonwebtoken::errors::Error as JwtErr;
  38. use lettre::address::AddressError as AddrErr;
  39. use lettre::error::Error as LettreErr;
  40. use lettre::transport::smtp::Error as SmtpErr;
  41. use openssl::error::ErrorStack as SSLErr;
  42. use regex::Error as RegexErr;
  43. use reqwest::Error as ReqErr;
  44. use serde_json::{Error as SerdeErr, Value};
  45. use std::io::Error as IoErr;
  46. use std::time::SystemTimeError as TimeErr;
  47. use u2f::u2ferror::U2fError as U2fErr;
  48. use webauthn_rs::error::WebauthnError as WebauthnErr;
  49. use yubico::yubicoerror::YubicoError as YubiErr;
  50. #[derive(Serialize)]
  51. pub struct Empty {}
  52. // Error struct
  53. // Contains a String error message, meant for the user and an enum variant, with an error of different types.
  54. //
  55. // After the variant itself, there are two expressions. The first one indicates whether the error contains a source error (that we pretty print).
  56. // The second one contains the function used to obtain the response sent to the client
  57. make_error! {
  58. // Just an empty error
  59. Empty(Empty): _no_source, _serialize,
  60. // Used to represent err! calls
  61. Simple(String): _no_source, _api_error,
  62. // Used for special return values, like 2FA errors
  63. Json(Value): _no_source, _serialize,
  64. Db(DieselErr): _has_source, _api_error,
  65. R2d2(R2d2Err): _has_source, _api_error,
  66. U2f(U2fErr): _has_source, _api_error,
  67. Serde(SerdeErr): _has_source, _api_error,
  68. JWt(JwtErr): _has_source, _api_error,
  69. Handlebars(HbErr): _has_source, _api_error,
  70. //WsError(ws::Error): _has_source, _api_error,
  71. Io(IoErr): _has_source, _api_error,
  72. Time(TimeErr): _has_source, _api_error,
  73. Req(ReqErr): _has_source, _api_error,
  74. Regex(RegexErr): _has_source, _api_error,
  75. Yubico(YubiErr): _has_source, _api_error,
  76. Lettre(LettreErr): _has_source, _api_error,
  77. Address(AddrErr): _has_source, _api_error,
  78. Smtp(SmtpErr): _has_source, _api_error,
  79. OpenSSL(SSLErr): _has_source, _api_error,
  80. DieselCon(DieselConErr): _has_source, _api_error,
  81. DieselMig(DieselMigErr): _has_source, _api_error,
  82. Webauthn(WebauthnErr): _has_source, _api_error,
  83. }
  84. impl std::fmt::Debug for Error {
  85. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  86. match self.source() {
  87. Some(e) => write!(f, "{}.\n[CAUSE] {:#?}", self.message, e),
  88. None => match self.error {
  89. ErrorKind::Empty(_) => Ok(()),
  90. ErrorKind::Simple(ref s) => {
  91. if &self.message == s {
  92. write!(f, "{}", self.message)
  93. } else {
  94. write!(f, "{}. {}", self.message, s)
  95. }
  96. }
  97. ErrorKind::Json(_) => write!(f, "{}", self.message),
  98. _ => unreachable!(),
  99. },
  100. }
  101. }
  102. }
  103. impl Error {
  104. pub fn new<M: Into<String>, N: Into<String>>(usr_msg: M, log_msg: N) -> Self {
  105. (usr_msg, log_msg.into()).into()
  106. }
  107. pub fn empty() -> Self {
  108. Empty {}.into()
  109. }
  110. pub fn with_msg<M: Into<String>>(mut self, msg: M) -> Self {
  111. self.message = msg.into();
  112. self
  113. }
  114. pub const fn with_code(mut self, code: u16) -> Self {
  115. self.error_code = code;
  116. self
  117. }
  118. }
  119. pub trait MapResult<S> {
  120. fn map_res(self, msg: &str) -> Result<S, Error>;
  121. }
  122. impl<S, E: Into<Error>> MapResult<S> for Result<S, E> {
  123. fn map_res(self, msg: &str) -> Result<S, Error> {
  124. self.map_err(|e| e.into().with_msg(msg))
  125. }
  126. }
  127. impl<E: Into<Error>> MapResult<()> for Result<usize, E> {
  128. fn map_res(self, msg: &str) -> Result<(), Error> {
  129. self.and(Ok(())).map_res(msg)
  130. }
  131. }
  132. impl<S> MapResult<S> for Option<S> {
  133. fn map_res(self, msg: &str) -> Result<S, Error> {
  134. self.ok_or_else(|| Error::new(msg, ""))
  135. }
  136. }
  137. #[allow(clippy::unnecessary_wraps)]
  138. const fn _has_source<T>(e: T) -> Option<T> {
  139. Some(e)
  140. }
  141. fn _no_source<T, S>(_: T) -> Option<S> {
  142. None
  143. }
  144. fn _serialize(e: &impl serde::Serialize, _msg: &str) -> String {
  145. serde_json::to_string(e).unwrap()
  146. }
  147. fn _api_error(_: &impl std::any::Any, msg: &str) -> String {
  148. let json = json!({
  149. "Message": msg,
  150. "error": "",
  151. "error_description": "",
  152. "ValidationErrors": {"": [ msg ]},
  153. "ErrorModel": {
  154. "Message": msg,
  155. "Object": "error"
  156. },
  157. "ExceptionMessage": null,
  158. "ExceptionStackTrace": null,
  159. "InnerExceptionMessage": null,
  160. "Object": "error"
  161. });
  162. _serialize(&json, "")
  163. }
  164. //
  165. // Rocket responder impl
  166. //
  167. use std::io::Cursor;
  168. use rocket::http::{ContentType, Status};
  169. use rocket::request::Request;
  170. use rocket::response::{self, Responder, Response};
  171. impl<'r> Responder<'r> for Error {
  172. fn respond_to(self, _: &Request) -> response::Result<'r> {
  173. match self.error {
  174. ErrorKind::Empty(_) => {} // Don't print the error in this situation
  175. ErrorKind::Simple(_) => {} // Don't print the error in this situation
  176. _ => error!(target: "error", "{:#?}", self),
  177. };
  178. let code = Status::from_code(self.error_code).unwrap_or(Status::BadRequest);
  179. Response::build().status(code).header(ContentType::JSON).sized_body(Cursor::new(format!("{}", self))).ok()
  180. }
  181. }
  182. //
  183. // Error return macros
  184. //
  185. #[macro_export]
  186. macro_rules! err {
  187. ($msg:expr) => {{
  188. error!("{}", $msg);
  189. return Err(crate::error::Error::new($msg, $msg));
  190. }};
  191. ($usr_msg:expr, $log_value:expr) => {{
  192. error!("{}. {}", $usr_msg, $log_value);
  193. return Err(crate::error::Error::new($usr_msg, $log_value));
  194. }};
  195. }
  196. #[macro_export]
  197. macro_rules! err_code {
  198. ($msg:expr, $err_code: expr) => {{
  199. error!("{}", $msg);
  200. return Err(crate::error::Error::new($msg, $msg).with_code($err_code));
  201. }};
  202. ($usr_msg:expr, $log_value:expr, $err_code: expr) => {{
  203. error!("{}. {}", $usr_msg, $log_value);
  204. return Err(crate::error::Error::new($usr_msg, $log_value).with_code($err_code));
  205. }};
  206. }
  207. #[macro_export]
  208. macro_rules! err_discard {
  209. ($msg:expr, $data:expr) => {{
  210. std::io::copy(&mut $data.open(), &mut std::io::sink()).ok();
  211. return Err(crate::error::Error::new($msg, $msg));
  212. }};
  213. ($usr_msg:expr, $log_value:expr, $data:expr) => {{
  214. std::io::copy(&mut $data.open(), &mut std::io::sink()).ok();
  215. return Err(crate::error::Error::new($usr_msg, $log_value));
  216. }};
  217. }
  218. #[macro_export]
  219. macro_rules! err_json {
  220. ($expr:expr, $log_value:expr) => {{
  221. return Err(($log_value, $expr).into());
  222. }};
  223. }
  224. #[macro_export]
  225. macro_rules! err_handler {
  226. ($expr:expr) => {{
  227. error!(target: "auth", "Unauthorized Error: {}", $expr);
  228. return ::rocket::request::Outcome::Failure((rocket::http::Status::Unauthorized, $expr));
  229. }};
  230. ($usr_msg:expr, $log_value:expr) => {{
  231. error!(target: "auth", "Unauthorized Error: {}. {}", $usr_msg, $log_value);
  232. return ::rocket::request::Outcome::Failure((rocket::http::Status::Unauthorized, $usr_msg));
  233. }};
  234. }