- Updated: December 28, 2025
- 7 min read
Rust Error Handling Without Dependencies – A Comprehensive Guide
Rust error handling without third‑party dependencies can be achieved using only the standard library by leveraging enums, the Result type, and the #[track_caller] attribute to provide rich context, location, and custom error kinds.

Why This News Matters for Rust Developers
On December 27 2025, a detailed post titled “Rust Errors Without Dependencies” was published, highlighting a minimalist approach to error handling that avoids popular crates such as anyhow or thiserror. The article sparked discussion across the Rust community because it tackles two pressing concerns: security‑focused supply‑chain risk and the desire for a universally understandable error strategy. You can read the original analysis here.
Why Error Handling Is Critical in Rust
Rust’s promise of memory safety and zero‑cost abstractions hinges on how developers manage failure. Unlike languages that rely on exceptions, Rust forces you to handle errors explicitly, which yields:
- Predictable control flow: Every
Resultmust be examined, preventing hidden crashes. - Supply‑chain resilience: Fewer third‑party crates mean a smaller attack surface.
- Better observability: When errors carry location and context, debugging becomes faster.
These benefits align with the broader industry shift toward secure, maintainable codebases—especially for startups and SMBs that rely on lean stacks. For example, the UBOS solutions for SMBs emphasize minimal dependencies to keep deployments lightweight and auditable.
Standard‑Library‑Only Error Handling: Enums, Location Tracking, and Context
The original article demonstrates a three‑step pattern that stays within the Rust standard library:
1️⃣ Define a Typed Error Enum
Encapsulate every possible failure in a single enum. This makes the error surface exhaustive and self‑documenting.
use std::fmt::{Display, Formatter};
use std::error::Error;
#[derive(Debug)]
pub enum DemoError {
ParseErr(std::num::ParseIntError),
IoErr(std::io::Error),
}
impl From for DemoError {
fn from(err: std::num::ParseIntError) -> Self {
DemoError::ParseErr(err)
}
}
impl From for DemoError {
fn from(err: std::io::Error) -> Self {
DemoError::IoErr(err)
}
}
impl Error for DemoError {}
impl Display for DemoError {
fn fmt(&self, f: &mut Formatter) > Result<(), std::fmt::Error> {
match self {
DemoError::ParseErr(e) => write!(f, "Parse error: {}", e),
DemoError::IoErr(e) => write!(f, "IO error: {}", e),
}
}
}
2️⃣ Capture Call‑Site Location with #[track_caller]
Rust 1.46 introduced Location::caller(), which can be stored in the error struct to report the exact file and line where the failure originated.
use std::panic::Location;
#[derive(Debug)]
pub struct DemoError {
kind: DemoErrorKind,
location: &'static Location,
}
#[derive(Debug)]
pub enum DemoErrorKind {
ParseErr(std::num::ParseIntError),
IoErr(std::io::Error),
}
impl From for DemoError {
#[track_caller]
fn from(err: std::num::ParseIntError) -> Self {
DemoError {
kind: DemoErrorKind::ParseErr(err),
location: Location::caller(),
}
}
}
3️⃣ Add Context Manually with .map_err()
When a function can fail for multiple reasons, you can enrich the error with the offending input value.
fn parse_number(input: &str) -> Result<i32, DemoError> {
input
.parse()
.map_err(|_| DemoError::new(DemoErrorKind::FirstNumberErr(input.to_string())))
}
By combining these three techniques, developers obtain error messages that include:
- What went wrong (error kind)
- Where it happened (file & line)
- Why it happened (the problematic input)
All of this is achievable without pulling in a single external crate, keeping the binary size low and the supply chain clean.
Rust vs. Node.js: How the Approaches Diverge
Node.js relies on try / catch blocks and untyped Error objects. A single uncaught exception can bring down an entire server, as illustrated by the pre‑Express 5 crash scenario:
import express from 'express';
const app = express();
app.get('/', async (req, res) => {
throw new Error('failed!'); // crashes the process in older Express
res.send('Hello World!');
});
app.listen(3000);
In contrast, Rust forces the programmer to handle each Result at the call site, making silent failures impossible. The trade‑off is a bit more boilerplate, but the payoff is deterministic reliability—critical for services where uptime is non‑negotiable.
When developers do choose third‑party crates in Rust, they typically reach for:
- anyhow: ergonomic error handling with automatic context.
- thiserror: derives
Errorimplementations for enums. - eyre: similar to anyhow but with backtrace support.
While these crates are battle‑tested, the original article argues that the standard library already provides the essential building blocks, especially when security and binary size are top priorities.
Practical Example: A Small CLI That Parses Two Numbers
Below is a complete, dependency‑free program that demonstrates the three‑step pattern. It parses two user‑supplied strings, reports precise errors, and exits gracefully.
use std::{error::Error, fmt::{Display, Formatter}, panic::Location};
#[derive(Debug)]
pub struct DemoError {
kind: DemoErrorKind,
location: &'static Location,
}
#[derive(Debug)]
pub enum DemoErrorKind {
FirstNumberErr(String),
SecondNumberErr(String),
IoErr(std::io::Error),
}
impl DemoError {
#[track_caller]
fn new(kind: DemoErrorKind) -> Self {
DemoError {
kind,
location: Location::caller(),
}
}
}
impl Display for DemoError {
fn fmt(&self, f: &mut Formatter) -> Result {
match &self.kind {
DemoErrorKind::FirstNumberErr(val) => write!(
f,
"Failed to parse first number '{}' at {}",
val,
self.location
),
DemoErrorKind::SecondNumberErr(val) => write!(
f,
"Failed to parse second number '{}' at {}",
val,
self.location
),
DemoErrorKind::IoErr(e) => write!(f, "IO error: {} at {}", e, self.location),
}
}
}
impl Error for DemoError {}
fn parse_input(input: &str, which: usize) -> Result {
input
.parse()
.map_err(|_| {
if which == 1 {
DemoError::new(DemoErrorKind::FirstNumberErr(input.to_string()))
} else {
DemoError::new(DemoErrorKind::SecondNumberErr(input.to_string()))
}
})
}
fn main() -> Result {
let args: Vec = std::env::args().collect();
if args.len() != 3 {
return Err(DemoError::new(DemoErrorKind::IoErr(
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Provide exactly two numbers",
),
)));
}
let a = parse_input(&args[1], 1)?;
let b = parse_input(&args[2], 2)?;
println!("Sum: {}", a + b);
Ok(())
}
Running the binary with cargo run -- 12 abc yields:
Failed to parse second number 'abc' at src/main.rs:45:22
The output instantly tells the developer which argument failed and where the error originated—no external crate required.
Benefits and Trade‑offs of a Dependency‑Free Strategy
| Benefit | Trade‑off |
|---|---|
| Reduced attack surface – no third‑party code to audit. | More boilerplate – manual context handling. |
| Predictable binary size – essential for embedded or WASM targets. | Potentially less ergonomic than anyhow‘s .context(). |
| Universal readability – every Rustacean knows the std‑lib pattern. | Steeper learning curve for newcomers unfamiliar with #[track_caller]. |
For many production teams, especially those building Enterprise AI platform by UBOS, the security advantage outweighs the extra lines of code. When rapid prototyping is required, developers may still reach for anyhow to save time, but they should be ready to replace it before shipping.
Conclusion: Adopt a Minimalist, Secure Error Strategy Today
Rust’s standard library already equips you with everything needed to build robust, context‑rich error handling without pulling in external crates. By defining typed enums, leveraging #[track_caller], and adding manual context, you gain:
- Clear, actionable error messages.
- Full control over binary size and supply‑chain risk.
- Code that is instantly understandable by any Rust developer.
If you’re evaluating whether to adopt this approach for your next project, consider the following steps:
- Audit existing dependencies for security exposure.
- Refactor critical modules to use the std‑only pattern.
- Run integration tests that assert error messages contain location and context.
Ready to accelerate your development while keeping the stack lean? Explore the UBOS solutions for SMBs that provide a low‑code environment built on the same principles of minimal dependencies and high reliability. For teams that need AI‑driven insights, our AI marketing agents integrate seamlessly with Rust back‑ends, delivering real‑time analytics without extra baggage.
Curious about pricing or want a quick start? Check out the UBOS pricing plans to find a tier that matches your security and performance goals.
Stay tuned for more deep‑dives into Rust best practices, and feel free to share your own experiences in the comments below. Secure, efficient error handling is a community effort—let’s build safer software together.
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.