BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / error.rs

error.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
error.rs 1.8 KiB Download Raw
1use serde_json::Value;
2
3pub type Result<T> = std::result::Result<T, Error>;
4
5#[derive(Debug, thiserror::Error)]
6pub 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} from {url}: {message}")]
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
28impl 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)]
44mod 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 from https://graph.microsoft.com/v1.0/me: Forbidden");
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}