My Rust Backend Exited With Code 0 While the Database Was Down

The database was down, the backend printed nothing and exited 0. Three small mistakes with map_err, unwrap and a missing .await made a failing service look healthy. How errors should travel up to main, and the one test that catches it.

Simone Negro, Backend & AI Developer
6 min read

I stopped the database, started my Rust backend and waited for an error. Nothing was printed. echo $? said 0. As far as anything watching the process could tell, it had started and stopped cleanly, while it never even reached the database.

It took three different mistakes to get there, all small and all common when you are new to Rust’s error handling. This post explains why the exit code matters, how an error is supposed to travel up to main, the three ways I broke that, and the test that now catches all of them. The examples come from a small demo project that reproduces each bug, so every output below is real.

Why the exit code matters

The exit code is how a process tells the rest of the system whether it worked. A human reads the error message; everything else reads the number. 0 means success, anything else means failure, and a lot of tooling acts on that distinction without ever looking at the text:

  • A container restart policy like on-failure restarts the service only when it exits with a non-zero code.
  • A shell script with set -e, or a CI step, stops at the first command that fails, and “fails” means non-zero.
  • A deploy that starts the new version and checks it exited cleanly believes whatever number it gets.

A backend that exits 0 when it couldn’t reach its database is lying to all of them. Nothing restarts it, nothing stops the pipeline, and the first sign of trouble is a user.

How an error gets from a function to main

Rust’s main can return a Result. When it returns Err, Rust prints the error to stderr and exits with code 1. So the whole job is to make sure that every error reaches main, and the ? operator is the tool for it: on Ok it unwraps the value, on Err it returns from the current function right away, handing the error to the caller.

use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    connect("postgres://127.0.0.1:5432/app").await?;
    Ok(())
}

With the database down, this one does the right thing:

Error: "cannot connect to postgres://127.0.0.1:5432/app: connection refused"
exit code: 1

That’s the baseline. Here are three ways to lose it.

Mistake 1: map_err without ?

I wanted a clearer message, so I reached for map_err:

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    connect("postgres://127.0.0.1:5432/app")
        .await
        .map_err(|e| format!("database unreachable: {e}"));
    Ok(())
}
exit code: 0

map_err rewrites the error, and that’s all it does. It returns a new Result with a different error inside, and that Result still has to go somewhere. Without ? it goes nowhere: the line ends, execution continues, and main returns Ok(()). The compiler did warn me:

warning: unused `Result` that must be used

I read it as noise. It was the whole bug.

The three tools that look alike are worth keeping apart:

ToolWhat it does with an ErrWhat you get back
map_err(...)rewrites it and keeps it inside the Resultstill a Result, still yours to handle
?returns it to the callerthe Ok value, unwrapped
.unwrap()panicsthe Ok value, unwrapped

Mistake 2: called Result::unwrap() on an Err value

Reading the config, I took the shortcut:

let config = read_config("missing.toml").unwrap();
thread 'main' panicked at src/bin/bug_unwrap.rs:3:57:
called `Result::unwrap()` on an `Err` value: "cannot read missing.toml: No such file or directory (os error 2)"
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
exit code: 101

At least it fails. But 101 is the code Rust uses for a panic, and a panic means “the program has a bug”, not “the input was wrong”. A missing config file is an expected situation with a clear message, and it deserves a normal error and code 1. I keep unwrap for cases that really can’t happen, and I write down why when I use it.

Mistake 3: a future that is never awaited

The third one was the strangest. I called an async function and forgot the .await:

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    connect("postgres://127.0.0.1:5432/app");
    Ok(())
}
exit code: 0

Calling an async fn doesn’t run it. It builds a future, a description of work that starts only when something awaits it. Without .await the connection attempt never happens, so it can’t fail either. This time the compiler is very direct:

warning: unused implementer of `Future` that must be used
  = note: futures do nothing unless you `.await` or poll them

There is a nastier version. Write let _ = connect(...); and the warning disappears, because let _ = tells the compiler you are ignoring the value on purpose. The program still exits 0, and now nobody tells you.

Why ? can also convert the error

One detail confused me while fixing all this. ? doesn’t only return the error: it converts it into the error type of the function, using the From trait. That’s why this works:

fn read_config(path: &str) -> Result<String, Box<dyn Error>> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {path}: {e}"))?;
    Ok(text)
}

After map_err, the error is a String. The function promises a Box<dyn Error>. The ? bridges the two. So map_err(...)? is the pattern: rewrite the message, then send it up.

Choosing the message format yourself

Returning a Result from main has one side effect I only noticed later: Rust prints the error with its Debug format. For a plain string that means quotes around the message, as in the baseline above. For some error types it means much more: in the previous post, a TOML error printed the entire config file.

So my main now handles the error itself, and the real work moved into a function that still returns Result:

use std::process::ExitCode;

async fn run() -> Result<(), Box<dyn Error>> {
    let _config = read_config("app.toml")?;
    connect("postgres://127.0.0.1:5432/app").await
}

#[tokio::main]
async fn main() -> ExitCode {
    if let Err(e) = run().await {
        eprintln!("{e}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}
cannot read app.toml: No such file or directory (os error 2)
exit code: 1

{e} uses Display, the format meant for people. Every function below main keeps using ?, and only the last step, from error to exit code, is written by hand.

The only test that sees a swallowed error

All three mistakes passed my unit tests, because my unit tests called functions. The functions were fine. The bug was in what main did with their result, and no unit test looks at that.

Cargo can build the real binary for an integration test and tell you where it is, through the CARGO_BIN_EXE_<name> environment variable. A test in tests/ can then run it like a user would and check the exit code and stderr:

use std::process::Command;

#[test]
fn fails_with_exit_code_1_and_a_message() {
    let output = Command::new(env!("CARGO_BIN_EXE_app")).output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert_eq!(Some(1), output.status.code(), "stderr: {stderr}");
    assert!(stderr.contains("cannot read app.toml"), "got: {stderr}");
}

To check that it actually guards anything, I pointed the same kind of test at the binary with the map_err bug. It failed, which is what it’s for:

assertion `left == right` failed: the binary hid the error

In my backend, the same kind of test runs the binary with no argument and with a config file that doesn’t exist. Both have to end with code 1 and a message, never 0 and never 101.

Test the exit code, not just the functions

Error handling in Rust is explicit, and that made me overconfident: if every function returns Result, surely errors can’t get lost. They can, in the last few lines, and the compiler’s warnings were the only thing pointing at them. I now treat unused Result and unused implementer of Future as errors in my head, and I keep one test that runs the binary for real. I’m still not sure that’s enough for the day the backend has many more ways to fail at startup, but it caught everything I’ve managed to break so far.

The same kind of quiet failure exists outside Rust too: an [Authorize] attribute that didn’t protect anything is the ASP.NET Core version of a system that reports success while doing the wrong thing.

References