This commit is contained in:
Simon
2026-01-02 14:55:13 +00:00
parent 27bb3daec4
commit 89eecbe790
6 changed files with 692 additions and 552 deletions

95
src/util/discord.rs Normal file
View File

@@ -0,0 +1,95 @@
use std::error::Error;
use std::fmt::Write as _;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;
/// Send a detailed error report to a Discord webhook
pub async fn send_discord_error_report<T: Error>(
error: &T,
context: Option<&str>, // e.g. provider name, URL, query
extra_info: Option<&str>, // any debug info you want
file: &str,
line: u32,
module: &str,
) {
let webhook_url = match std::env::var("DISCORD_WEBHOOK") {
Ok(url) => url,
Err(_) => return,
};
// Discord embed field limits
const MAX_FIELD: usize = 1024;
let mut error_chain = String::new();
let mut current: &dyn Error = error;
let mut i = 0;
loop {
let _ = writeln!(error_chain, "{}. {}", i + 1, current);
i += 1;
match current.source() {
Some(src) => current = src,
None => break,
}
}
let truncate = |s: &str| {
if s.len() > MAX_FIELD {
format!("{}", &s[..MAX_FIELD - 1])
} else {
s.to_string()
}
};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let payload = json!({
"embeds": [{
"title": "🚨 Rust Error Report",
"color": 0xE74C3C,
"fields": [
{
"name": "Error",
"value": truncate(&error.to_string()),
"inline": false
},
{
"name": "Error Chain",
"value": truncate(&error_chain),
"inline": false
},
{
"name": "Location",
"value": format!("`{}`:{}\n`{}`", file, line, module),
"inline": false
},
{
"name": "Context",
"value": truncate(context.unwrap_or("n/a")),
"inline": false
},
{
"name": "Extra Info",
"value": truncate(extra_info.unwrap_or("n/a")),
"inline": false
}
],
"footer": {
"text": format!("Unix time: {}", timestamp)
}
}]
});
// Send (never panic)
if let Err(e) = wreq::Client::new()
.post(webhook_url)
.json(&payload)
.send()
.await
{
eprintln!("Failed to send Discord error report: {e}");
}
}