rust
70 lines · 9 steps
Building a custom error type in Rust
A hand-rolled ConfigError enum implements Display, Error, and From so config parsing can use the `?` operator cleanly.
Explained by
highlit
1use std::fmt;
2
3#[derive(Debug)]
4pub enum ConfigError {
5 Io(std::io::Error),
6 Parse { field: String, source: std::num::ParseIntError },
7 Missing(String),
8}
9
10impl fmt::Display for ConfigError {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 match self {
13 ConfigError::Io(e) => write!(f, "failed to read config file: {e}"),
14 ConfigError::Parse { field, source } => {
15 write!(f, "invalid value for `{field}`: {source}")
16 }
17 ConfigError::Missing(field) => write!(f, "missing required field `{field}`"),
18 }
19 }
20}
21
22impl std::error::Error for ConfigError {
23 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
24 match self {
25 ConfigError::Io(e) => Some(e),
26 ConfigError::Parse { source, .. } => Some(source),
27 ConfigError::Missing(_) => None,
28 }
29 }
30}
31
32impl From<std::io::Error> for ConfigError {
33 fn from(e: std::io::Error) -> Self {
34 ConfigError::Io(e)
35 }
36}
37
38pub struct Config {
39 pub port: u16,
40 pub workers: u32,
41}
42
43pub fn load_config(path: &str) -> Result<Config, ConfigError> {
44 let contents = std::fs::read_to_string(path)?;
45
46 let mut port = None;
47 let mut workers = None;
48
49 for line in contents.lines() {
50 let Some((key, value)) = line.split_once('=') else {
51 continue;
52 };
53 let key = key.trim();
54 let value = value.trim();
55 let parsed = value.parse().map_err(|source| ConfigError::Parse {
56 field: key.to_string(),
57 source,
58 })?;
59 match key {
60 "port" => port = Some(parsed as u16),
61 "workers" => workers = Some(parsed),
62 _ => {}
63 }
64 }
65
66 Ok(Config {
67 port: port.ok_or_else(|| ConfigError::Missing("port".into()))?,
68 workers: workers.ok_or_else(|| ConfigError::Missing("workers".into()))?,
69 })
70}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modeling errors as an enum lets one type carry several distinct failure cases with their own data.
- 2Implementing Display, Error, and From turns a custom type into a first-class citizen of Rust's error ecosystem.
- 3A From impl is what makes the `?` operator automatically convert lower-level errors into your own type.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-custom-error-type-in-rust-explained-rust-4452/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.