| 1 | use serde_json::Value; |
| 2 | |
| 3 | pub type Result<T> = std::result::Result<T, Error>; |
| 4 | |
| 5 | #[derive(Debug, thiserror::Error)] |
| 6 | pub enum Error { |
| 7 | #[error("no browser on {endpoint}: {reason}")] |
| 8 | NoBrowser { endpoint: String, reason: String }, |
| 9 | #[error("no open Teams or Outlook tab in the browser")] |
| 10 | NoAppTab, |
| 11 | #[error("Microsoft 365 login required: {0}")] |
| 12 | LoginRequired(String), |
| 13 | #[error("no fresh token for {scope}{detail}")] |
| 14 | NoFreshToken { scope: String, detail: String }, |
| 15 | #[error("HTTP {status}: {message} ({url})")] |
| 16 | Api { |
| 17 | status: u16, |
| 18 | url: String, |
| 19 | message: String, |
| 20 | body: Box<Value>, |
| 21 | }, |
| 22 | #[error("browser protocol error: {0}")] |
| 23 | Cdp(String), |
| 24 | #[error("tab connection lost during a write ({0}); check whether it was sent before retrying")] |
| 25 | WriteInterrupted(String), |
| 26 | } |
| 27 | |
| 28 | impl Error { |
| 29 | pub fn api(status: u16, url: &str, body: Value) -> Self { |
| 30 | let message = match body.pointer("/error/message").and_then(Value::as_str) { |
| 31 | Some(text) => text.to_owned(), |
| 32 | None => body.to_string().chars().take(300).collect(), |
| 33 | }; |
| 34 | Error::Api { |
| 35 | status, |
| 36 | url: url.to_owned(), |
| 37 | message, |
| 38 | body: Box::new(body), |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[cfg(test)] |
| 44 | mod tests { |
| 45 | use serde_json::json; |
| 46 | |
| 47 | use super::*; |
| 48 | |
| 49 | #[test] |
| 50 | fn api_error_uses_graph_message() { |
| 51 | let error = Error::api(403, "https://graph.microsoft.com/v1.0/me", json!({"error": {"message": "Forbidden"}})); |
| 52 | assert_eq!(error.to_string(), "HTTP 403: Forbidden (https://graph.microsoft.com/v1.0/me)"); |
| 53 | } |
| 54 | |
| 55 | #[test] |
| 56 | fn api_error_truncates_plain_bodies() { |
| 57 | let Error::Api { message, .. } = Error::api(0, "u", json!("x".repeat(1000))) else { |
| 58 | unreachable!() |
| 59 | }; |
| 60 | assert_eq!(message.chars().count(), 300); |
| 61 | } |
| 62 | } |