BlueGit

ict rusty-teams

Files

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

error.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
error.rs 1.9 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}: {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
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(
52 403,
53 "https://graph.microsoft.com/v1.0/me",
54 json!({"error": {"message": "Forbidden"}}),
55 );
56 assert_eq!(
57 error.to_string(),
58 "HTTP 403: Forbidden (https://graph.microsoft.com/v1.0/me)"
59 );
60 }
61
62 #[test]
63 fn api_error_truncates_plain_bodies() {
64 let Error::Api { message, .. } = Error::api(0, "u", json!("x".repeat(1000))) else {
65 unreachable!()
66 };
67 assert_eq!(message.chars().count(), 300);
68 }
69}