1use std::path::PathBuf;
2
3use thiserror::Error;
4
5pub type Result<T> = std::result::Result<T, NotifyError>;
6
7#[derive(Debug, Error)]
8pub enum NotifyError {
9 #[error("configuration file not found")]
10 ConfigNotFound,
11 #[error("failed to read configuration file {path}: {source}")]
12 ConfigRead {
13 path: PathBuf,
14 source: std::io::Error,
15 },
16 #[error("failed to parse configuration file {path}: {source}")]
17 ConfigParse {
18 path: PathBuf,
19 source: toml::de::Error,
20 },
21 #[error("channel \"{0}\" was not found")]
22 ChannelNotFound(String),
23 #[error("default_channel is not configured")]
24 DefaultChannelMissing,
25 #[error("{0}")]
26 InvalidInput(String),
27 #[error("{0}")]
28 Validation(String),
29 #[error("channel \"{channel}\" is missing environment variable {env}")]
30 MissingEnv { channel: String, env: String },
31 #[error("channel type \"{0}\" is not available for sending yet")]
32 UnsupportedProvider(String),
33 #[error("channel type \"{channel_type}\" does not support attachments")]
34 UnsupportedAttachment { channel_type: String },
35 #[error("HTTP request failed: {0}")]
36 Http(#[source] reqwest::Error),
37 #[error("provider request failed: {0}")]
38 Provider(String),
39 #[error("I/O error at {path}: {source}")]
40 Io {
41 path: PathBuf,
42 source: std::io::Error,
43 },
44 #[error("failed to serialize JSON output: {0}")]
45 Json(#[from] serde_json::Error),
46}
47
48impl From<reqwest::Error> for NotifyError {
49 fn from(source: reqwest::Error) -> Self {
50 Self::Http(source.without_url())
51 }
52}
53
54impl NotifyError {
55 pub fn code(&self) -> &'static str {
56 match self {
57 Self::ConfigNotFound => "CONFIG_NOT_FOUND",
58 Self::ConfigRead { .. } => "CONFIG_READ",
59 Self::ConfigParse { .. } => "CONFIG_PARSE",
60 Self::ChannelNotFound(_) => "CHANNEL_NOT_FOUND",
61 Self::DefaultChannelMissing => "DEFAULT_CHANNEL_MISSING",
62 Self::InvalidInput(_) => "INVALID_INPUT",
63 Self::Validation(_) => "VALIDATION",
64 Self::MissingEnv { .. } => "MISSING_ENV",
65 Self::UnsupportedProvider(_) => "UNSUPPORTED_PROVIDER",
66 Self::UnsupportedAttachment { .. } => "UNSUPPORTED_ATTACHMENT",
67 Self::Http(_) => "HTTP",
68 Self::Provider(_) => "PROVIDER",
69 Self::Io { .. } => "IO",
70 Self::Json(_) => "JSON",
71 }
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[tokio::test]
80 async fn reqwest_errors_do_not_leak_request_url() {
81 let secret_url = "http://127.0.0.1:1/discord-webhook/secret-token";
82 let reqwest_error = reqwest::Client::new()
83 .post(secret_url)
84 .send()
85 .await
86 .unwrap_err();
87
88 assert!(reqwest_error.to_string().contains(secret_url));
89
90 let notify_error = NotifyError::from(reqwest_error);
91 let message = notify_error.to_string();
92
93 assert!(message.contains("HTTP request failed"));
94 assert!(!message.contains(secret_url));
95 assert!(!message.contains("secret-token"));
96 }
97}