Module 6 · Nullability & error handling
6.3Panics, custom errors, thiserror & anyhow
When Rust code should panic instead of returning an error, how to define your own error types, and when to use the thiserror and anyhow crates.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A bug, such as a broken precondition | throw new RangeError(...) | throw new ArgumentOutOfRangeException(...) | panic!, assert!, expect: the program stops |
| A failure the caller should expect | throw, just like a bug | throw, just like a bug | Return Result<T, E> |
| Your own error type | class ConfigError extends Error | class ConfigException : Exception | An enum that implements Display and std::error::Error |
| Error types for a library | Exported error classes | Custom exception classes | An enum with #[derive(Error)] from thiserror |
| Errors in an application | Wrap with new Error(message, { cause }), log the chain | Wrap with an inner exception, log the chain | anyhow::Result<T> and .context(...) |
TypeScriptC# uses exceptions for two different things: bugs, like an index out of range or an argument that breaks the rules, and failures you can expect, like a missing file or a typo in user input. Rust splits them. Expected failures are Result values, which the previous lesson covered. Bugs panic: the program stops with a message, because no caller could sensibly carry on. This lesson covers panics, then how to give your errors real types, and the two widely used crates that help: thiserror for libraries and anyhow for applications.
Panics are for bugs
A precondition that the caller broke is a bug in the caller. Here’s a progress bar that requires done to be at most total:
function renderBar(done: number, total: number): string {
if (done > total) {
throw new RangeError(`done (${done}) is more than total (${total})`);
}
return `[${"#".repeat(done)}${"-".repeat(total - done)}]`;
}
console.log(renderBar(3, 10));Console.WriteLine(RenderBar(3, 10));
static string RenderBar(int done, int total)
{
ArgumentOutOfRangeException.ThrowIfGreaterThan(done, total);
return $"[{new string('#', done)}{new string('-', total - done)}]";
}fn render_bar(done: usize, total: usize) -> String {
assert!(done <= total, "done ({done}) is more than total ({total})");
format!("[{}{}]", "#".repeat(done), "-".repeat(total - done))
}
fn main() {
println!("{}", render_bar(3, 10));
}Output
[###-------]
assert!(condition, message) panics if the condition is false. Without it, total - done would still panic in a debug build, with a message about subtraction overflow, but the message wouldn’t tell the caller what they did wrong. If someone calls render_bar(12, 10):
fn main() {
println!("{}", render_bar(12, 10)); // panics
println!("never printed");
}the program prints a panic message to stderr, with the thread, the file and line of the assert!, and done (12) is more than total (10). Then it unwinds: it walks back up the stack, dropping every value on the way, so files close and memory is freed. A panic on the main thread ends the process with exit code 101. A panic on another thread ends only that thread, and whoever joins it gets an error.
You’ll meet panics from several places:
panic!("message"), and the asserting macrosassert!,assert_eq!andassert_ne!.unwrap()andexpect(...)on aNoneor anErr.- Indexing out of bounds:
scores[10]on a shorterVec. (scores.get(10)returns anOptioninstead.) - Integer overflow in debug builds, and division by zero.
unreachable!()for code that can’t run if your logic is right, andtodo!()for code you haven’t written yet. Both compile anywhere, because their type is!, the never type.
Mental model shiftA panic is not an exception
There’s no catch for a panic in everyday code. std::panic::catch_unwind exists for the edges of a program, like a thread pool that must survive one bad task, but it isn’t a try. A project can even set panic = "abort" in Cargo.toml to skip unwinding altogether. So don’t panic for anything a caller might want to handle: if a typo in a config file could cause it, return a Result.
In .NET terms: what you’d throw ArgumentException, ArgumentOutOfRangeException or InvalidOperationException for is a panic in Rust; what you’d throw FormatException, FileNotFoundException or HttpRequestException for is a Result.
In TypeScript terms: what you’d throw RangeError or TypeError for, the errors that mean “this code is wrong”, is a panic in Rust; what you’d throw for bad input, a missing file or a failed request is a Result.
Your own error type
For expected failures, the error is a value, so it should have a type the caller can inspect. The Rust convention is an enum with one variant per kind of failure, plus two trait implementations:
Display: the message for a human, used by{}and.to_string().std::error::Error: marks the type as an error and, throughsource(), links to the lower-level error that caused it, if any. That’s Rust’s version ofcauseInnerException.
Here’s a config reader whose callers can tell a missing key from a bad value:
class ConfigError extends Error {}
class MissingKeyError extends ConfigError {
key: string;
constructor(key: string) {
super(`missing key '${key}'`);
this.key = key;
}
}
class BadPortError extends ConfigError {
value: string;
constructor(value: string) {
super(`bad port '${value}'`);
this.value = value;
}
}
function loadPort(config: string): number {
const value = config
.split("\n")
.find((line) => line.startsWith("port="))
?.slice("port=".length);
if (value === undefined) {
throw new MissingKeyError("port");
}
const port = Number(value);
if (!Number.isInteger(port)) {
throw new BadPortError(value);
}
return port;
}
for (const config of ["host=a\nport=8080", "host=a", "port=http"]) {
try {
console.log(`port ${loadPort(config)}`);
} catch (error) {
if (!(error instanceof ConfigError)) throw error;
console.log(`error: ${error.message}`);
}
}foreach (var config in new[] { "host=a\nport=8080", "host=a", "port=http" })
{
try
{
Console.WriteLine($"port {LoadPort(config)}");
}
catch (ConfigException error)
{
Console.WriteLine($"error: {error.Message}");
}
}
static int LoadPort(string config)
{
var value = config.Split('\n').FirstOrDefault(line => line.StartsWith("port="))?.Substring(5);
if (value is null)
{
throw new MissingKeyException("port");
}
try
{
return int.Parse(value);
}
catch (FormatException inner)
{
throw new BadPortException(value, inner);
}
}
abstract class ConfigException(string message, Exception? inner = null) : Exception(message, inner);
class MissingKeyException(string key) : ConfigException($"missing key '{key}'")
{
public string Key { get; } = key;
}
class BadPortException(string value, Exception inner) : ConfigException($"bad port '{value}'", inner)
{
public string Value { get; } = value;
}use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
MissingKey(String),
BadPort {
value: String,
source: ParseIntError,
},
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::MissingKey(key) => write!(f, "missing key '{key}'"),
ConfigError::BadPort { value, .. } => write!(f, "bad port '{value}'"),
}
}
}
impl std::error::Error for ConfigError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConfigError::MissingKey(_) => None,
ConfigError::BadPort { source, .. } => Some(source),
}
}
}
fn load_port(config: &str) -> Result<u16, ConfigError> {
let value = config
.lines()
.find_map(|line| line.strip_prefix("port="))
.ok_or_else(|| ConfigError::MissingKey(String::from("port")))?;
value.parse().map_err(|source| ConfigError::BadPort {
value: value.to_string(),
source,
})
}
fn main() {
for config in ["host=a\nport=8080", "host=a", "port=http"] {
match load_port(config) {
Ok(port) => println!("port {port}"),
Err(error) => println!("error: {error}"),
}
}
}Output
port 8080 error: missing key 'port' error: bad port 'http'
The enum is the whole list of ways load_port can fail, and it’s in the signature. A caller can match on ConfigError::MissingKey(key) the way TypeScriptC# code would check instanceof MissingKeyErrorcatch MissingKeyException, but the compiler knows every variant, so a match that forgets one doesn’t compile. It also means no instanceof check and rethrow for errors you didn’t expect: nothing else can come out of load_port.
#[derive(Debug)] is required too: the Error trait needs Debug, which is what main prints if it returns the error.
BadPort keeps the original ParseIntError as its source, but its message doesn’t repeat it. That’s the convention: each error describes its own level, and code that wants the full story follows source() down the chain. anyhow, below, does that for you.
thiserror: the same enum, derived
The Display and Error impls above are 17 lines of boilerplate for a two-variant enum, and they grow with every variant. The thiserror crate writes them for you from attributes:
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key '{0}'")]
MissingKey(String),
#[error("bad port '{value}'")]
BadPort {
value: String,
#[source]
source: ParseIntError,
},
}Output
port 8080 error: missing key 'port' error: bad port 'http'
#[derive(Error)]implementsstd::error::Error.#[error("...")]on each variant implementsDisplay. It’s a format string:{0}is the first field of a tuple variant,{value}a named field, and{value:?}works too.#[source]marks the field thatsource()returns. (A field namedsourceis picked up even without it.)
For a variant that only wraps another error, #[from] also writes the From impl, so ? converts the lower-level error for you:
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum LimitError {
#[error("limit is not a number")]
NotANumber(#[from] ParseIntError),
#[error("limit {0} is over the maximum of 100")]
TooHigh(u32),
}
fn parse_limit(text: &str) -> Result<u32, LimitError> {
let limit: u32 = text.parse()?; // ParseIntError becomes LimitError::NotANumber
if limit > 100 {
return Err(LimitError::TooHigh(limit));
}
Ok(limit)
}
fn main() {
for text in ["50", "five", "500"] {
match parse_limit(text) {
Ok(limit) => println!("limit {limit}"),
Err(error) => println!("error: {error}"),
}
}
}Output
limit 50 error: limit is not a number error: limit 500 is over the maximum of 100
#[from] implies #[source], and the variant can’t have other fields besides the source; that’s why BadPort above, which also stores the text, uses #[source] and map_err instead.
anyhow: one error type for applications
In a library, callers need to know which error happened, so they can react. At the top of an application, you usually just need to stop and say what went wrong, with enough context to fix it. Defining enums for that is busywork. The anyhow crate gives you a single error type that can hold any error, plus a way to add context as it goes up:
function start(name: string, config: string): number {
try {
return loadPort(config);
} catch (error) {
throw new Error(`loading ${name}`, { cause: error });
}
}
function describe(error: unknown): string {
const messages: string[] = [];
for (let current: unknown = error; current instanceof Error; current = current.cause) {
messages.push(current.message);
}
return messages.join(": ");
}
for (const [name, config] of [["a.conf", "port=8080"], ["b.conf", "host=example.com"]] as const) {
try {
console.log(`listening on ${start(name, config)}`);
} catch (error) {
console.log(`error: ${describe(error)}`);
}
}foreach (var (name, config) in new[] { ("a.conf", "port=8080"), ("b.conf", "host=example.com") })
{
try
{
Console.WriteLine($"listening on {Start(name, config)}");
}
catch (Exception error)
{
Console.WriteLine($"error: {Describe(error)}");
}
}
static int Start(string name, string config)
{
try
{
return LoadPort(config);
}
catch (MissingKeyException error)
{
throw new InvalidOperationException($"loading {name}", error);
}
}
static string Describe(Exception error) =>
error.InnerException is { } inner ? $"{error.Message}: {Describe(inner)}" : error.Message;
use anyhow::{Context, Result};
fn start(name: &str, config: &str) -> Result<u16> {
let port = load_port(config).with_context(|| format!("loading {name}"))?;
Ok(port)
}
fn main() {
for (name, config) in [("a.conf", "port=8080"), ("b.conf", "host=example.com")] {
match start(name, config) {
Ok(port) => println!("listening on {port}"),
Err(error) => println!("error: {error:#}"),
}
}
}Output
listening on 8080 error: loading b.conf: missing key 'port'
load_port is the thiserror version from above, and start is application code:
anyhow::Result<T>is short forResult<T, anyhow::Error>.anyhow::Errorholds any error type that implementsstd::error::Error(and isSend + Sync + 'static, which ordinary error types are), so?accepts all of them, much likeBox<dyn Error>..context("...")and.with_context(|| ...)wrap the error in a message that says what you were doing, keeping the original as itssource. Usewith_contextwhen the message needsformat!, so it’s only built on failure. Both also work on anOption, turningNoneinto an error.{error:#}prints the whole chain on one line, joined by": ". TypeScriptC# needs thedescribehelper for that.
Two macros round it out: bail!("...") returns an error early, like throw, and ensure!(condition, "...") returns one if a condition is false, like assert! but without the panic.
The three ways to print an anyhow::Error show different amounts:
use anyhow::{Context, Result};
fn parse_port(value: &str) -> Result<u16> {
value.parse().with_context(|| format!("bad port '{value}'"))
}
fn main() {
let error = parse_port("http").context("loading app.conf").unwrap_err();
println!("{error}");
println!("---");
println!("{error:#}");
println!("---");
println!("{error:?}");
}Output
loading app.conf
---
loading app.conf: bad port 'http': invalid digit found in string
---
loading app.conf
Caused by:
0: bad port 'http'
1: invalid digit found in stringThe last form is what you get when fn main() -> anyhow::Result<()> returns an error: Rust prints Error: followed by it, which makes anyhow the usual choice for main in command-line tools. (If the RUST_BACKTRACE or RUST_LIB_BACKTRACE environment variable is set to 1, {:?} also prints a stack backtrace after the causes.)
If application code does need to check for one specific error, it still can: error.downcast_ref::<ConfigError>() returns Some(&ConfigError) when that’s what’s inside. But if callers regularly need to tell errors apart, that’s the sign you want an enum.
Which one should I use?
The split most Rust projects follow: libraries define error enums with thiserror; applications use anyhow; bugs panic. A project can do both, as in the example above: its own modules return enums, and main collects everything into anyhow with context.
| What | When | Why | How |
|---|---|---|---|
panic!, assert! | A bug: a broken precondition or a state your logic says can’t happen. | No caller can fix a bug at run time. The message points at the line. | assert!(done <= total, "done ({done}) is more than total ({total})") |
expect("why") | An Option or Result that can’t be None or Err unless there’s a bug. | Documents the assumption, and panics with it if it’s wrong. | DEFAULT_PORT.parse().expect("DEFAULT_PORT is a valid port") |
unreachable!(), todo!() | Code that can’t run if the logic is right; code not written yet. | Type-checks anywhere, and panics with a clear message if reached. | _ => unreachable!("checked above") |
Error enum with thiserror | A library, or any module whose callers need to react differently to different failures. | Callers can match on variants; the type documents every failure. | #[derive(Debug, Error)], #[error("...")] per variant, #[from] or #[source] for wrapped errors. |
| Error enum by hand | You can’t add a dependency, or you want to see what thiserror generates. | Same result as thiserror, more code. | impl Display and impl std::error::Error (with source). |
anyhow::Result<T> with .context(...) | Application code: main, commands, request handlers, scripts. | ? accepts any error; context explains what you were doing; {:#} and {:?} print the chain. | load(path).with_context(|| format!("loading {path}"))? |
Box<dyn Error> | Small programs, examples and tests, with no extra crate. | Built in; ? accepts any error. No context, and the message from main is less readable. | fn main() -> Result<(), Box<dyn Error>> |
Result<T, String> | Quick code where an error is only ever shown, never inspected. | Simple, but callers can’t match on it and the cause is lost. | .map_err(|error| format!("bad port: {error}"))? |
Rule of thumb: panic only for bugs. For everything else, return a Result. Give a library’s errors an enum with thiserror, so callers can match on them. In application code, use anyhow::Result and add .context(...) wherever the error would otherwise leave the reader asking “while doing what?”.
Is it a bug: a broken precondition, or a state your code should make impossible?
YesNoPanic:
assert!,expect("why"),unreachable!()The program stops with a message pointing at the line. Never for bad input.Are you writing a library, or will callers want to react differently to different failures?
YesNoAn error enum with
thiserror#[error("...")]for each message,#[from]so?converts the errors underneath.Is it a quick example or test, with no extra crates?
YesNoResult<T, Box<dyn Error>>?works on any error, but there's no context.Otherwise: Application code that reports errors rather than inspecting them:
anyhow::Result<T>, with.context(...)as errors go up
Under the hood
A panic calls the panic hook, which prints the message, then unwinds: each stack frame is cleaned up and its values dropped, as if every function returned at once. On the main thread, the process then exits with code 101. With panic = "abort" in a [profile] in Cargo.toml, the message is still printed, but then the process aborts at once instead of unwinding: no cleanup runs, and the binary is a little smaller.
thiserror runs at compile time. It generates the same Display, Error and From impls you’d write by hand, so it adds no run-time cost, and your public API doesn’t mention it: switching between hand-written impls and thiserror doesn’t change anything for your callers.
anyhow::Error is one pointer wide. It keeps the pointer to its methods’ table in the heap allocation, next to the error, so a Result that holds it stays small. A Box<dyn Error> is a pointer to the error plus a pointer to its methods’ table:
use std::error::Error;
println!("Box<dyn Error>: {}", size_of::<Box<dyn Error>>());
println!("anyhow::Error: {}", size_of::<anyhow::Error>());
println!("anyhow::Result<()>: {}", size_of::<anyhow::Result<()>>());Output
Box<dyn Error>: 16 anyhow::Error: 8 anyhow::Result<()>: 8
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Box<dyn Error> | pointer to the error8 bytes | pointer to the methods8 bytes | 16 bytes | ||||||||||||||
anyhow::Error | pointer to error + methods8 bytes | 8 bytes | |||||||||||||||
anyhow::Result<()> | pointer for Err, 0 for Ok8 bytes | 8 bytes | |||||||||||||||
Three values, on a 64-bit target. A Box of dyn Error is 16 bytes today: an 8-byte pointer to the error and an 8-byte pointer to the table of its methods. An anyhow::Error is 8 bytes, one pointer, because anyhow keeps the pointer to the method table in the heap allocation, next to the error. anyhow::Result of unit is also 8 bytes today: the pointer is never 0, so Ok is stored as 0 and needs no tag.
On a 64-bit target, Box<dyn Error> is two pointers today (the language itself only promises at least one). The one-pointer anyhow::Error is a documented design choice of the crate, and the 8-byte anyhow::Result<()> is what today’s compiler makes of it. Either way, returning an error costs about as much as returning a pointer.
Common pitfalls
Common pitfallanyhow in a library's API
A library function that returns anyhow::Result tells callers “something went wrong” but not what. They can’t match on it, only print it or guess with downcast_ref. Return your own thiserror enum from public functions, and leave anyhow to the application that calls you.
Common pitfallTwo #[from] for the same source type
#[from] writes impl From<ParseIntError> for LimitError. Put it on two variants with the same source type, and there are two such impls, which Rust doesn’t allow:
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error)]
enum LimitError {
#[error("bad minimum")]
BadMinimum(#[from] ParseIntError),
#[error("bad maximum")]
BadMaximum(#[from] ParseIntError),
}Rust doesn't compile this: error E0119
error[E0119]: conflicting implementations of trait `From<ParseIntError>` for type `LimitError`
--> main.rs:9:18
|
7 | BadMinimum(#[from] ParseIntError),
| ---- first implementation here
8 | #[error("bad maximum")]
9 | BadMaximum(#[from] ParseIntError),
| ^^^^ conflicting implementation for `LimitError`? couldn’t know which variant you meant. Use #[source] on both and pick the variant at the call with .map_err(LimitError::BadMinimum)?; a tuple variant’s name works as a function.
Common pitfallThrowing the cause away
.map_err(|_| format!("bad port '{value}'")) compiles, but the _ discards the reason: was the port empty, not a number, or too big? Keep the original error as a #[source] field, or with anyhow, use .context(...), which adds your message and keeps the cause. And print anyhow errors with {:#} or {:?}: plain {} shows only the outermost message.
Try it yourself
Exercise: port this to Rust
Port this sign-up check to Rust. Write a NameError enum with thiserror, a check_name function that returns Result<&str, NameError>, and a sign_up function that returns anyhow::Result<String> and adds the line number as context.
class NameError extends Error {}
const MAX = 12;
function checkName(name: string): string {
if (name.length === 0) {
throw new NameError("name is empty");
}
if (name.length > MAX) {
throw new NameError(`name is ${name.length} characters; the limit is ${MAX}`);
}
const bad = [...name].find((c) => !/[a-z0-9_]/.test(c));
if (bad !== undefined) {
throw new NameError(`'${bad}' is not allowed in a name`);
}
return name;
}
function signUp(line: number, name: string): string {
try {
return `welcome, ${checkName(name)}`;
} catch (error) {
throw new Error(`line ${line}`, { cause: error });
}
}
function describe(error: unknown): string {
const messages: string[] = [];
for (let current: unknown = error; current instanceof Error; current = current.cause) {
messages.push(current.message);
}
return messages.join(": ");
}
const names = ["ada_l", "", "grace_hopper_1906", "Linus"];
names.forEach((name, index) => {
try {
console.log(signUp(index + 1, name));
} catch (error) {
console.log(`error: ${describe(error)}`);
}
});string[] names = ["ada_l", "", "grace_hopper_1906", "Linus"];
for (var index = 0; index < names.Length; index++)
{
try
{
Console.WriteLine(SignUp(index + 1, names[index]));
}
catch (Exception error)
{
Console.WriteLine($"error: {Describe(error)}");
}
}
static string CheckName(string name)
{
const int Max = 12;
if (name.Length == 0)
{
throw new NameException("name is empty");
}
if (name.Length > Max)
{
throw new NameException($"name is {name.Length} characters; the limit is {Max}");
}
foreach (var c in name)
{
if (!(char.IsAsciiLetterLower(c) || char.IsAsciiDigit(c) || c == '_'))
{
throw new NameException($"'{c}' is not allowed in a name");
}
}
return name;
}
static string SignUp(int line, string name)
{
try
{
return $"welcome, {CheckName(name)}";
}
catch (NameException error)
{
throw new InvalidOperationException($"line {line}", error);
}
}
static string Describe(Exception error) =>
error.InnerException is { } inner ? $"{error.Message}: {Describe(inner)}" : error.Message;
class NameException(string message) : Exception(message);Expected output
welcome, ada_l error: line 2: name is empty error: line 3: name is 17 characters; the limit is 12 error: line 4: 'L' is not allowed in a name
Show a hint
Give NameError three variants with #[error(...)] messages: Empty, TooLong with length and max fields, and BadChar(char). check_name returns Result<&str, NameError>; sign_up returns anyhow::Result<String> and adds the line number with with_context. Print errors with {:#}.
Show a solution
use anyhow::Context;
use thiserror::Error;
const MAX: usize = 12;
#[derive(Debug, Error)]
enum NameError {
#[error("name is empty")]
Empty,
#[error("name is {length} characters; the limit is {max}")]
TooLong { length: usize, max: usize },
#[error("'{0}' is not allowed in a name")]
BadChar(char),
}
fn check_name(name: &str) -> Result<&str, NameError> {
if name.is_empty() {
return Err(NameError::Empty);
}
let length = name.chars().count();
if length > MAX {
return Err(NameError::TooLong { length, max: MAX });
}
let allowed = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_';
if let Some(bad) = name.chars().find(|&c| !allowed(c)) {
return Err(NameError::BadChar(bad));
}
Ok(name)
}
fn sign_up(line: usize, name: &str) -> anyhow::Result<String> {
let name = check_name(name).with_context(|| format!("line {line}"))?;
Ok(format!("welcome, {name}"))
}
fn main() {
let names = ["ada_l", "", "grace_hopper_1906", "Linus"];
for (index, name) in names.into_iter().enumerate() {
match sign_up(index + 1, name) {
Ok(message) => println!("{message}"),
Err(error) => println!("error: {error:#}"),
}
}
}check_name is library-style code: its callers might want to tell an empty name from a bad character, so it returns a NameError enum, and thiserror writes the messages. sign_up is application code, so it uses anyhow and adds context saying which line failed. {:#} prints the context and the NameError message joined by a colon, just like the describe helper.
Saved in this browser only.