skip to content

In a Rust payment library, why return Result<T, PaymentError> with an error enum instead of Result<T, String>?

level: juniorimportance: must knowfreq 68%

answer

  1. callers branch, not parse
  2. one variant per caller reaction
  3. match checks every variant
  4. String is not an Error

basics

~20 s

An error enum gives each failure a variant with its own data, so callers match on Declined, Network or InvalidCard instead of parsing text; rustc checks every variant is handled, and the enum can implement std::error::Error, which String does not.

solid answer

~40 s

A `String` error carries a message for people and nothing for code: a caller that wants to retry a network failure but ask for another card on a decline has to compare text, which breaks the moment the wording changes. A `PaymentError` enum gives each failure a variant — `Declined { code: u16 }`, `Network(io::Error)`, `InvalidCard` — so the caller writes a `match`, reads the decline code as a typed `u16`, and rustc rejects a `match` that forgets a variant with E0004. The enum can also implement `Display` for the message and `std::error::Error`, so it can be another error's `source()`, be boxed into `Box<dyn Error>` and be recovered by downcasting. `String` does not implement `std::error::Error`; it only becomes an error by being boxed into an opaque `Box<dyn Error>`.

code

rust · 36 lines
rust
use std::fmt;

#[derive(Debug)]
pub enum PaymentError {
    Declined { code: u16 },
    Network(std::io::Error),
    InvalidCard,
}

impl fmt::Display for PaymentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PaymentError::Declined { code } => write!(f, "payment declined (code {code})"),
            PaymentError::Network(_) => write!(f, "could not reach the payment gateway"),
            PaymentError::InvalidCard => write!(f, "card number failed validation"),
        }
    }
}

impl std::error::Error for PaymentError {}

fn charge(card: &str) -> Result<u64, PaymentError> {
    if card.len() != 16 {
        return Err(PaymentError::InvalidCard);
    }
    Err(PaymentError::Declined { code: 51 })
}

fn main() {
    match charge("4111111111111111") {
        Ok(id) => println!("charged, receipt {id}"),
        Err(PaymentError::Declined { code }) => println!("declined ({code}): try another card"),
        Err(PaymentError::Network(e)) => println!("retry later: {e}"),
        Err(PaymentError::InvalidCard) => println!("check the card number"),
    }
}

go deeper

for a junior

Recall the shape: one enum, one variant per failure a caller would handle differently, data inside the variant, and a match at the call site that rustc checks for completeness.

for a middle

Explain what String costs: no typed fields, no exhaustiveness check, no std::error::Error impl and so no source chain or downcast, then show the Display and Error impls that make the enum a proper error.

for a senior

Show that you size variants by the caller's decision rather than by internal cause: decline, network and validation failures each need a different reaction, while many internal parse failures can share one variant.

for a principal

Treat the enum as a contract callers compile against: which failures you promise to distinguish is an API decision, and splitting variants too finely freezes internal detail into that contract.

## What a `String` error loses Rust has no exceptions: a fallible function returns `Result<T, E>`, and the **error type** `E` is part of its signature. The cheapest choice is `Result<T, String>` — return `Err(format!("declined: {code}"))` and move on. It compiles, it prints, and it hides almost everything a caller needs: - **No branching without parsing.** A checkout page retries a network failure, asks for another card on a decline and highlights the card field on a validation failure. With a `String`, each of those decisions is a substring test that silently breaks when someone rewords a message. - **No typed data.** A decline code arrives as digits inside text, not as a `u16` the caller can compare. - **No compiler help.** Nothing tells a caller that a new kind of failure now exists. - **No error machinery.** `String` does not implement `std::error::Error`, so it cannot be another error's `source()` or the target of `downcast_ref`. The `From<String>` impl for `Box<dyn Error>` wraps it in a private type, so the text survives but its identity does not. ## The enum shape An **error enum** has one variant per failure a caller would react to differently, and each variant carries the data that reaction needs: ```rust #[derive(Debug)] pub enum PaymentError { Declined { code: u16 }, Network(std::io::Error), InvalidCard, } ``` - `Declined { code: u16 }` is a **struct-like variant**: the gateway's reason code travels as a number. - `Network(std::io::Error)` is a **tuple variant** that keeps the underlying I/O failure instead of flattening it into text. - `InvalidCard` is a **unit variant**: the name says everything. The function signature becomes `fn charge(card: &str) -> Result<u64, PaymentError>`, and the type now documents every failure the call can report as an `Err`. ## What the compiler does for callers A caller handles the result with `match` or `if let`, and the patterns destructure the variant directly: ```rust match charge(card) { Ok(id) => println!("charged, receipt {id}"), Err(PaymentError::Declined { code }) => println!("declined ({code})"), Err(PaymentError::Network(e)) => println!("retry later: {e}"), Err(PaymentError::InvalidCard) => println!("check the card number"), } ``` `match` must be **exhaustive**. Leave out the `InvalidCard` arm and rustc refuses to compile, with error E0004: `` non-exhaustive patterns: `Err(PaymentError::InvalidCard)` not covered ``. A wildcard arm (`Err(_) => ...`) opts out of that check on purpose, which is the right call when a caller genuinely treats the remaining failures alike. ## Making the enum a real error An enum on its own is just data. Two impls turn it into an error that the rest of the ecosystem understands: 1. `impl fmt::Display for PaymentError` — the human-readable message, written by hand with one `write!` per variant (std has no derive for `Display`). 2. `impl std::error::Error for PaymentError {}` — an empty block is enough, because the trait requires `Debug` and `Display` and gives every method a default. With those in place, `?` can convert a `PaymentError` into a `Box<dyn Error>` at an application's top level, another error can return it from `source()`, and `downcast_ref::<PaymentError>()` can recover it from a boxed error. ## Choosing between the options | Error type | Callers can branch on it | Typed data | Implements `std::error::Error` | |---|---|---|---| | `String` | only by comparing text | no | no | | `()` | no — every failure looks the same | no | no | | `Box<dyn Error>` | only by downcasting | only after downcasting | it holds one; the box itself is not an `Error` | | `PaymentError` enum | yes, with `match` | yes, in variant fields | yes, once you write the impls | The Rust API Guidelines go further and say never to use `()` as an error type; if a failure carries no data, a unit struct with `Display` and `Error` impls is the replacement. ## Where a `String` is still acceptable A throwaway script or a binary's `main` that only prints and exits can live with `Box<dyn Error>` and string messages, because nobody branches on the failure. A **library** is different: its callers are other programs, and the error type is the main channel through which their code learns what went wrong. That is why a payment library's public functions return `Result<T, PaymentError>`.

  • Why not use `()` as the error type when a failure carries no data?
    `()` implements neither `Display` nor `std::error::Error`, so it cannot be printed as a message, chained as a `source()` or boxed into `Box<dyn Error>` by `?`, and its `Debug` output says nothing. The Rust API Guidelines say never to use it as an error type; define a unit struct such as `CardExpired` and implement `Display` and `Error` for it.
  • Can a caller handle only `Declined` and pass every other `PaymentError` on?
    Yes: match `Err(PaymentError::Declined { code })` and add `Err(other) => return Err(other)`. That catch-all arm opts out of exhaustiveness, so a variant added to `PaymentError` later lands in it silently instead of being flagged by E0004 — acceptable when the caller truly treats the rest alike.

  • A String error is fine because callers can check the message text.
  • String implements std::error::Error, so it chains like any other error.
  • Rewording a String error message can never break a caller.
  • Display for an error enum can be derived from std like Debug.
  • A missing match arm for a new variant only causes a warning.