_CORE
AI & Agentic Systems Core Information Systems Cloud & Platform Engineering Data Platform & Integration Security & Compliance QA, Testing & Observability IoT, Automation & Robotics Mobile & Digital Banking & Finance Insurance Public Administration Defense & Security Healthcare Energy & Utilities Telco & Media Manufacturing Logistics & E-commerce Retail & Loyalty
References Technologies Blog Know-how Tools
About Collaboration Careers
CS EN
Let's talk

Rust Error Handling

20. 08. 2022 1 min read intermediate

Rust nemá exceptions. Místo toho Result a Option — explicitní, type-safe error handling.

Result a Option

use std::fs; fn read_config(path: &str) -> Result { fs::read_to_string(path) } fn find_user(id: u32) -> Option { users.iter().find(|u| u.id == id).cloned() } // ? operátor — propagace chyby fn process() -> Result<(), Box> { let config = fs::read_to_string(“config.toml”)?; let data: Config = toml::from_str(&config)?; Ok(()) }

Custom error types

use thiserror::Error;

[derive(Error, Debug)]

enum AppError {

[error(“User not found: {0}”)]

UserNotFound(u32),

[error(“Database error”)]

Database(#[from] sqlx::Error),

[error(“Invalid input: {0}”)]

Validation(String), }

Key Takeaway

Result pro chyby, Option pro nullable. ? operátor pro propagaci. thiserror pro custom error types.

rusterror handlingprogramming
Share:

CORE SYSTEMS tým

Stavíme core systémy a AI agenty, které drží provoz. 15 let zkušeností s enterprise IT.