Quick answer: Call std::panic::set_hook before App::new().run(). Inside the hook, read the message from info.payload(), the file and line from info.location(), and capture a backtrace with std::backtrace::Backtrace::force_capture(). Write the report to a file first, try one blocking POST with a short timeout, and send any leftover file on the next launch. The hook is process-wide, so it covers panics on Bevy’s task pool threads too.
A Bevy game that panics on a player’s machine prints one line to a console the player does not have: thread 'Compute Task Pool (3)' panicked at src/enemy.rs:88:31. Then the window closes. What reaches you is “it crashed”, with no file, no line and no idea which system was running. Rust gives you a place to intercept that moment, and the panic location is baked into the binary even when everything else is stripped. This guide builds a small crash reporting module around a panic hook. It is engine-agnostic Rust, so the same file works in Bevy, macroquad, ggez or a custom wgpu renderer.
- What a Rust panic hook sees in a Bevy game
- Dependencies and the release profile
- The panic hook: message, location and backtrace
- Send now if you can, on the next launch if you cannot
- Installing it in a Bevy app
- Getting readable backtraces from release builds
- What a panic hook cannot see
- Where the reports go
- Related guides
- Frequently asked questions
What a Rust panic hook sees in a Bevy game
A panic hook is a function Rust calls when a panic starts, before unwinding or aborting. It is global to the process, which matters for Bevy because your systems do not run on the main thread. They run on task pool threads, and the hook fires on whichever thread panicked.
The hook covers most of what kills a Rust game in practice:
unwrap()andexpect()on aNoneorErr, the single most common cause.- Out-of-bounds indexing, integer overflow in debug builds, and
RefCelldouble borrows. - Explicit
panic!,unreachable!,todo!and failedassert!. - Libraries that panic on misuse. wgpu, for example, panics on an uncaptured validation error by default.
It runs whether your profile uses panic = "unwind" or panic = "abort". With abort the hook runs first and the process dies afterwards.
Dependencies and the release profile
The module needs an HTTP client and a JSON builder. ureq is a small blocking client, which is what you want inside a hook: there is no async runtime to keep alive while the process is dying.
# Cargo.toml
[dependencies]
ureq = { version = "2", features = ["json"] }
serde_json = "1"
[profile.release]
debug = "line-tables-only"
The examples use ureq 2. ureq 3 reorganized the request builder (headers and timeouts are set differently), so pin the major version or adapt the send function. The profile setting keeps line tables in the release binary so the backtrace has file names and line numbers; more on the cost below.
The panic hook: message, location and backtrace
Create src/crash_report.rs. The first half is the sender and a helper that makes titles stable.
use std::backtrace::Backtrace;
use std::fs;
use std::path::PathBuf;
use std::time::Duration;
const ENDPOINT: &str = "https://api.bugnet.io/api/bugs/submit";
const API_KEY: &str = "sk_live_your_project_key";
const GAME_VERSION: &str = env!("CARGO_PKG_VERSION");
fn pending_path() -> PathBuf {
std::env::temp_dir().join("my_game_pending_crash.json")
}
/// Ok when the report was delivered or permanently rejected,
/// Err when it is worth trying again later (offline, timeout).
fn send(report: &serde_json::Value) -> Result<(), ()> {
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(5))
.build();
match agent
.post(ENDPOINT)
.set("X-API-Key", API_KEY)
.send_json(report)
{
Ok(_) | Err(ureq::Error::Status(_, _)) => Ok(()),
Err(ureq::Error::Transport(_)) => Err(()),
}
}
/// Collapse digits so "index 7 of 3" and "index 9 of 4" share a title.
fn stable(message: &str) -> String {
let mut out = String::new();
let mut in_digits = false;
for c in message.lines().next().unwrap_or("").chars().take(160) {
if c.is_ascii_digit() {
if !in_digits {
out.push('N');
}
in_digits = true;
} else {
out.push(c);
in_digits = false;
}
}
out
}
send separates two failures. A transport error means the player is offline or the request timed out, and the report is worth keeping. An HTTP error status means the server answered and refused, and retrying the same body on every launch would never succeed.
stable exists because of how bug trackers group reports. index out of bounds: the len is 3 but the index is 7 and the same panic with len is 5 are one bug. Collapsing the digits gives both the title the len is N but the index is N, so a tracker that groups by title shows one report with a count instead of a page of near-duplicates.
Now the hook itself:
pub fn install() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
// Print the usual message first so the console is not held up by the network.
default_hook(info);
let message = if let Some(s) = info.payload().downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = info.payload().downcast_ref::<String>() {
s.clone()
} else {
"panic with a non-string payload".to_string()
};
let location = info
.location()
.map(|l| format!("{}:{}", l.file(), l.line()))
.unwrap_or_else(|| "unknown location".to_string());
let thread = std::thread::current()
.name()
.unwrap_or("unnamed")
.to_string();
let backtrace = Backtrace::force_capture();
let report = serde_json::json!({
"title": format!("panic at {location}: {}", stable(&message)),
"description": format!(
"{message}\n\nthread: {thread}\nlocation: {location}\n\n{backtrace}"
),
"category": "crash",
"priority": "critical",
"auto_captured": true,
"platform": std::env::consts::OS,
"os_info": format!("{} {}", std::env::consts::OS, std::env::consts::ARCH),
"game_version": GAME_VERSION,
});
// Durable first: the file survives even if the send below never finishes.
let _ = fs::write(pending_path(), report.to_string());
if send(&report).is_ok() {
let _ = fs::remove_file(pending_path());
}
}));
}
Details that are easy to get wrong:
- The payload is not always a
&str.panic!("literal")carries a&'static str,panic!("{x}")andunwrap()on anErrcarry aString. Check both. location()does not depend on debug info. The file, line and column of the panic site are compiled into the binary. A stripped build still reportssrc/enemy.rs:88, which is why the title is built from it.force_capture()ignoresRUST_BACKTRACE. PlainBacktrace::capture()returns an empty backtrace unless the player set that environment variable, which they did not.- The thread name is worth a line. In Bevy it tells you whether the panic came from the main thread, a compute task or an async asset task.
- Call the previous hook. It prints the standard panic message, which you still want in a terminal and in any log the launcher captures.
- Nothing in the hook may panic. A panic inside a panic hook aborts the process on the spot. That is why every fallible call is
let _ =oris_ok(), neverunwrap().
Send now if you can, on the next launch if you cannot
The hook writes the report to disk before it touches the network. That order is the whole design. The process is about to die, the player may be offline, and with panic = "abort" or a second panic there is no guarantee the request finishes. A file survives all of that. The POST inside the hook is a best-effort extra with a five second timeout, so the game never hangs on exit for long.
The second half of the module picks up whatever was left behind:
/// Call once at startup: delivers a crash the previous run could not send.
pub fn send_pending() {
let path = pending_path();
let Ok(text) = fs::read_to_string(&path) else {
return;
};
let Ok(report) = serde_json::from_str::<serde_json::Value>(&text) else {
let _ = fs::remove_file(&path);
return;
};
std::thread::spawn(move || {
if send(&report).is_ok() {
let _ = fs::remove_file(&path);
}
});
}
/// A report the player asked for. Never blocks the frame.
pub fn send_player_report(title: String, description: String) {
let report = serde_json::json!({
"title": title,
"description": description,
"platform": std::env::consts::OS,
"game_version": GAME_VERSION,
});
std::thread::spawn(move || {
let _ = send(&report);
});
}
The example keeps the pending file in the temp directory to stay dependency-free. In a real game put it next to your save files, where the OS will not clean it up between sessions.
Installing it in a Bevy app
Install the hook as the first thing in main, before the app is built, so a panic during plugin setup is covered as well.
// src/main.rs
use bevy::prelude::*;
mod crash_report;
fn main() {
crash_report::install();
crash_report::send_pending();
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Update, report_hotkey)
.run();
}
fn report_hotkey(keys: Res<ButtonInput<KeyCode>>) {
if keys.just_pressed(KeyCode::F8) {
crash_report::send_player_report(
"Player report (F8)".to_string(),
"Sent with the report hotkey.".to_string(),
);
}
}
The hotkey system uses ButtonInput, which is the input resource name from Bevy 0.13 onwards. Nothing in crash_report.rs depends on Bevy, so engine upgrades do not touch it.
send_player_report spawns a thread because a system runs inside the frame. A blocking HTTP call there would freeze the game for as long as the request takes. For anything beyond a hotkey, build the description from your own state: the current level, the player position, the seed. A fixed title such as “Player report (F8)” stacks every press into one report, which is fine for a jam build; put the level name in the title once you want them separated.
To test the crash path, add panic!("crash test") behind a debug key, build with cargo build --release, run the binary outside of cargo, and check three things: the report arrives, the pending file is gone, and with the network unplugged the report arrives on the next launch instead.
Getting readable backtraces from release builds
A backtrace is a list of return addresses. Turning them into names takes two things, and they are separate:
- Function names come from the symbol table. They survive as long as you do not strip the binary.
- File names and line numbers come from debug info. Release builds leave it out unless you ask.
debug = "line-tables-only" is the cheapest setting that gives file and line for every frame. It makes the binary bigger but does not change the generated code or its speed. debug = true adds full variable information you do not need for a backtrace. If you set strip = true or strip = "symbols" to shrink the download, the backtrace falls back to bare addresses and only the panic location remains readable.
On Windows with the MSVC toolchain the debug info lives in a separate .pdb file. The backtrace captured at run time resolves names only if that file sits next to the executable. Either ship the .pdb, or accept address-only frames from Windows players and rely on the panic location. Whatever you choose, test it by panicking on purpose in the exact build you upload, on each platform, and reading what arrives.
What a panic hook cannot see
A panic is Rust’s own failure mechanism. Several ways for a game to die are not panics, and the hook never runs for them:
- Segmentation faults inside a graphics driver, an audio backend or any C library reached through FFI.
- Stack overflow. Rust detects it and aborts with a message, but it does not go through the panic hook.
- Out of memory. A failed allocation aborts the process by default.
- The OS killing the process, and the player ending a hung game from the task manager.
Catching those takes a signal or exception handler, usually in a separate watchdog process that writes a minidump. There are crates for that approach; it is more moving parts, and for most indie Rust games panics are the large majority of crashes. Start with the hook, and add native crash handling when your reports stop explaining your refunds.
WebAssembly is a different environment. std::backtrace has nothing to capture on wasm32-unknown-unknown, blocking HTTP clients do not work, and the module cannot keep running after a panic. Use console_error_panic_hook so the message reaches the browser console, and from your own hook start a browser fetch through web-sys without waiting for it. The browser completes the request on its own.
Where the reports go
The module posts to Bugnet’s public report API: POST /api/bugs/submit with the project key in X-API-Key and a JSON body. There is no Rust or Bevy SDK, and the hundred lines above are all the client you need. The key is an ingestion key, safe to compile into the binary, because it can file reports but cannot read them.
In the dashboard, panics with the same title stack into one report with an occurrence count, and every occurrence keeps its own platform, OS and game version. panic at src/enemy.rs:88 with 140 occurrences on 0.3.1 and none on 0.3.2 tells you the fix worked without asking anyone. Player reports from the hotkey arrive in the same list. From there you can assign and prioritize, send new reports to Discord, and publish fixed issues to a public tracker and changelog. The free plan covers one project and up to 100 bug reports. The quickstart shows where the key is, and the API explorer lets you try the request first.
Related guides
- Why Rust Game Developers Need Error Tracking
- A Bug Report API for Games: Submit Reports from Launchers, Servers and Tools
- Why Does My Game Crash Only in the Release Build?
- How to Strip Debug Symbols From Release Builds
- Can Crash Reporting Work Offline?
Frequently asked questions
How do I catch a panic in a Bevy game?
Install a hook with std::panic::set_hook before calling App::new().run(). The hook is process-wide, so it runs for a panic on any thread, including the task pool threads Bevy runs systems on. Keep the previous hook from std::panic::take_hook and call it so the normal message is still printed.
Does a Rust panic hook still run with panic = "abort"?
Yes. The hook runs first and the process aborts afterwards, so a hook that writes a file or sends a report works with both unwinding and aborting panics.
How do I get a backtrace in a Rust release build?
Call std::backtrace::Backtrace::force_capture() inside the hook, which captures a backtrace regardless of the RUST_BACKTRACE environment variable. For file names and line numbers, enable debug info in the release profile, for example debug = "line-tables-only", and do not strip the binary.
Does a panic hook catch segfaults and stack overflows?
No. A segmentation fault in a graphics driver or C library, a stack overflow and an out-of-memory abort are not panics, so the hook never runs. Those need a signal handler or an out-of-process crash handler that writes a dump.
Is there a Bugnet SDK for Bevy or Rust?
No. Rust games use Bugnet’s public HTTP API, one POST with an X-API-Key header and a JSON body. Any HTTP client works; the example in this guide uses ureq and serde_json.
The panic location is compiled into the binary, so even a fully stripped release build can tell you the file and line. Write the report to disk first and treat the network as a bonus.