In this lesson, you will learn how to leverage the Debug trait to expose deep internal state when your Rust program encounters unexpected failures.
The Role of Debugging in Errors
When your code encounters an error, your goal is usually twofold: provide a clean message to the user, but keep the technical "guts" of the error visible to yourself. While the Display trait is perfect for user-facing output (e.g., "File not found"), the Debug trait is designed specifically for developers. It allows you to see the exact structure of your data, including internal fields that aren't meant for end-users.
Implementation and Usage
To enable this, you derive Debug on your custom error types. This allows you to print the entire internal state using the {:?} formatter in your println! or eprintln! calls.
Consider a scenario where you have a database connection error. The user just needs to know the system is busy, but you need to know the specific port and error code:
#[derive(Debug)]
struct DatabaseError {
port: u16,
code: i32,
message: String,
}
fn connect() -> Result<(), DatabaseError> {
Err(DatabaseError {
port: 5432,
code: 404,
message: "Connection refused".to_string()
})
}
fn main() {
if let Err(e) = connect() {
// Use {:?} to inspect the internal structure during development
eprintln!("Internal Error Details: {:?}", e);
}
}
Why use Debug over Display for internals?
If you rely only on Display, you might manually format a string that hides important details like the port or the code. By using the derived Debug trait, you get a "free" representation of your struct. If you later add a new field to DatabaseError, Debug will automatically include that field in your error logs without you having to update a custom string formatter. This makes it an essential tool for "tracing" exactly what went wrong deep inside your logic.
Key Takeaway: Use the Debug trait and the {:?} formatter to expose hidden internal state for developer diagnostics, keeping user-facing messages clean while maintaining full visibility into your error structure.