- Updated: January 4, 2026
- 7 min read
Design‑First Error Handling in Rust: A New Approach
Stop Forwarding Errors, Start Designing Them: A Rust‑Centric Design‑First Guide

Rust error handling should be designed, not merely forwarded: separate machine‑readable error kinds from human‑readable context, and let each layer add low‑friction, actionable information.
Why the Current Rust Error Landscape Is Burning Out Developers
It’s 3 a.m., production is down, and the logs scream: Error: serialization error: expected ',' or '}' at line 3, column 7. The message tells you that JSON is broken, but it gives you no clue which component produced the error, which request triggered it, or whether a retry would help. This is the exact scenario described in the original article “Stop Forwarding Errors, Start Designing Them”. The problem isn’t Rust itself; it’s the prevailing practice of treating errors as hot potatoes—catch, wrap, and toss them up the call stack without a clear design.
In the Rust ecosystem, three major patterns dominate error handling: the std::error::Error trait, the thiserror crate, and the anyhow crate. Each solves a piece of the puzzle but also introduces blind spots that make debugging at 3 a.m. a nightmare and automated recovery a guessing game.
What the Original Article Got Right
- Std::error::Error is too opinionated: it forces a linear chain, ignoring tree‑like error sources such as multi‑field validation failures.
- Backtraces are expensive and often useless in async code: they show where an error originated, not the logical path it traveled.
- Provide/Request API adds runtime unpredictability: callers must guess which typed context an error will expose.
- thiserror categorizes by origin, not by action: callers cannot infer whether an error is retryable, permanent, or user‑visible.
- anyhow’s convenience erodes context: developers skip
.context()calls, losing crucial debugging data.
These observations form the foundation for a design‑first approach that serves both machines (automated recovery) and humans (debugging). Below we outline a concrete pattern that can be adopted today in any Rust codebase.
A Design‑First Error Model for Rust
The core idea is to split an error into two orthogonal parts:
- Machine‑readable
ErrorKindandErrorStatus: a flat enum that tells the runtime what to do (retry, abort, fallback). - Human‑readable context stack: a lightweight, zero‑cost trace of where the error was generated, enriched with key‑value pairs (user ID, request ID, operation name).
The Struct Blueprint
pub struct Error {
kind: ErrorKind,
status: ErrorStatus,
message: String,
operation: &'static str,
context: Vec<(&'static str, String)>,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
pub enum ErrorKind {
NotFound,
PermissionDenied,
RateLimited,
ValidationFailed,
// … extend as needed
}
pub enum ErrorStatus {
Permanent, // never retry
Temporary, // safe to retry
Persistent, // already retried, still failing
}
This design mirrors the successful pattern used by Apache OpenDAL and eliminates the need for deep enum hierarchies. The kind field is always actionable, while the context vector captures the “who, what, where” without the overhead of a full backtrace.
Ergonomic Context Capture
Rust’s #\[track_caller\] attribute gives us file/line information at zero cost. By wrapping error creation in a tiny helper macro, developers are forced to add meaningful context at every module boundary:
macro_rules! err {
($kind:expr, $msg:expr $(, $key:expr => $val:expr)*) => {{
let mut ctx = Vec::new();
$(
ctx.push(($key, $val.to_string()));
)*
Error {
kind: $kind,
status: ErrorStatus::Temporary,
message: $msg.to_string(),
operation: std::module_path!(),
context: ctx,
source: None,
}
}};
}
Example usage:
fn fetch_user(id: &str) -> Result<User, Error> {
db::query_user(id).map_err(|e| err!(
ErrorKind::NotFound,
format!("failed to fetch user {}", id),
"user_id" => id,
"db_error" => e.to_string()
))
}
The compiler now forces you to provide context; otherwise the code won’t compile. This eliminates the “I’ll add context later” pitfall that plagues anyhow.
Benefits for Machines and Humans
For Automated Recovery
- Flat
ErrorKindenables simple match statements (e.g.,if err.kind() == ErrorKind::RateLimited). ErrorStatusmakes retry policies explicit, removing heuristic checks.- No need to traverse deep enum trees or rely on runtime
providecalls.
For Human Debugging
- Context stack provides a readable breadcrumb:
task=7829 → fetch_user → connection refused. - Zero‑cost location capture via
#\[track_caller\]gives file and line numbers. - Logs become self‑documenting; no need to chase backtraces across async boundaries.
Step‑by‑Step Migration Guide
- Define a single error module: create
error.rswith the struct and enums above. - Replace
thiserrorenums: map each variant to anErrorKindvalue. - Introduce the
err!macro: use it at every public function boundary. - Update retry middleware: switch from pattern‑matching on concrete types to checking
err.kind()anderr.status(). - Adjust logging: serialize
err.contextas JSON for structured log pipelines. - Test end‑to‑end: simulate failures and verify that both machines (retry loops) and humans (log output) behave as expected.
Case Study: Refactoring a Rust‑Based Order Service
Imagine an e‑commerce order service that talks to a payment gateway, a inventory DB, and a notification system. The original code used anyhow::Result everywhere, resulting in logs like:
ERROR: payment failed: connection refused
After applying the design‑first model, the same failure is logged as:
ERROR: operation=process_order, kind=RateLimited, status=Temporary
context: [
("order_id", "ORD-12345"),
("user_id", "U-9876"),
("gateway", "Stripe"),
("error", "connection refused")
]
location: src/order_service.rs:78
The retry layer now simply checks err.kind() == ErrorKind::RateLimited and backs off, while the on‑call engineer can instantly see which order and which gateway caused the issue.
How UBOS Helps You Implement This Pattern
The UBOS platform overview provides a built‑in Workflow automation studio that can ingest structured error logs and trigger automated remediation based on ErrorKind. By exposing your error structs as JSON, you can connect them directly to UBOS’s Workflow automation studio without writing custom parsers.
For teams that need rapid prototyping, the UBOS templates for quick start include a pre‑configured “Error Reporter” template that:
- Collects
ErrorKindandcontextvia a webhook. - Routes
RateLimitederrors to a retry queue. - Sends
PermissionDeniedalerts to Slack or Teams.
If you’re a startup, the UBOS for startups plan gives you 10,000 free error events per month, perfect for testing this new design. SMBs can leverage the UBOS solutions for SMBs to integrate error reporting with existing ticketing systems.
Moreover, the Enterprise AI platform by UBOS can enrich error context with AI‑generated insights—think automatic root‑cause suggestions based on historical patterns.
Boost Your Error‑Handling Workflow with UBOS Templates
UBOS’s marketplace offers ready‑made AI‑powered tools that complement the design‑first error model:
- AI SEO Analyzer – automatically scans your documentation for missing error‑handling guidelines.
- AI Article Copywriter – helps you generate clear error‑handling documentation.
- AI Chatbot template – can be wired to your error API to answer developer questions in real time.
- GPT-Powered Telegram Bot – receive instant alerts on critical
ErrorKind::Permanentevents.
By integrating these templates with the Telegram integration on UBOS and the ChatGPT and Telegram integration, you can create a feedback loop where developers get AI‑enhanced suggestions directly in their messaging workflow.
Take the Next Step
If you’re ready to stop forwarding errors and start designing them, begin by reviewing the original deep‑dive article here. Then, explore UBOS’s ecosystem:
- Read the About UBOS page to understand the team behind the platform.
- Check out the UBOS pricing plans to find a tier that matches your error‑volume needs.
- Visit the UBOS partner program if you want to co‑create custom error‑handling solutions.
- Browse the UBOS portfolio examples for real‑world implementations.
Adopt a design‑first error strategy today, and turn those 3 a.m. panic logs into actionable, machine‑friendly signals.
Andrii Bidochko
CTO UBOS
Andrii Bidochko is an AI entrepreneur and researcher focused on AI agents, reinforcement learning, and autonomous systems. He writes about the technologies shaping the future of machine intelligence, from frontier models and agent architectures to real-world AI applications.