Chapter 6: Error Handling & Design Patterns

Robust error handling and well-designed patterns are essential for production Rust applications. This chapter covers advanced error handling techniques and common design patterns.

6.1 Custom Error Types

Manual Error Implementation

use std::fmt;

#[derive(Debug)]
enum DatabaseError {
    ConnectionFailed(String),
    QueryFailed(String),
    NotFound,
}

impl fmt::Display for DatabaseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DatabaseError::ConnectionFailed(msg) => {
                write!(f, "Connection failed: {}", msg)
            }
            DatabaseError::QueryFailed(msg) => {
                write!(f, "Query failed: {}", msg)
            }
            DatabaseError::NotFound => {
                write!(f, "Record not found")
            }
        }
    }
}

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

fn query_database(id: u64) -> Result<String, DatabaseError> {
    if id == 0 {
        Err(DatabaseError::NotFound)
    } else {
        Ok(format!("User {}", id))
    }
}

Using thiserror

use thiserror::Error;

#[derive(Error, Debug)]
enum AppError {
    #[error("Database error: {0}")]
    Database(#[from] DatabaseError),

    #[error("IO error")]
    Io(#[from] std::io::Error),

    #[error("Invalid configuration: {field}")]
    InvalidConfig { field: String },

    #[error("User {id} not found")]
    UserNotFound { id: u64 },
}

fn load_user(id: u64) -> Result<String, AppError> {
    if id == 0 {
        return Err(AppError::UserNotFound { id });
    }
    Ok(format!("User {}", id))
}

6.2 Error Conversion and Propagation

Using anyhow for Applications

use anyhow::{Context, Result, bail};

fn read_config(path: &str) -> Result<Config> {
    let content = std::fs::read_to_string(path)
        .context("Failed to read config file")?;

    let config: Config = serde_json::from_str(&content)
        .context("Failed to parse config")?;

    if config.port == 0 {
        bail!("Invalid port number");
    }

    Ok(config)
}

#[derive(serde::Deserialize)]
struct Config {
    port: u16,
    host: String,
}
thiserror vs anyhow

Custom Error Context

trait ResultExt<T> {
    fn with_context<F, S>(self, f: F) -> Result<T, String>
    where
        F: FnOnce() -> S,
        S: Into<String>;
}

impl<T, E: fmt::Display> ResultExt<T> for Result<T, E> {
    fn with_context<F, S>(self, f: F) -> Result<T, String>
    where
        F: FnOnce() -> S,
        S: Into<String>,
    {
        self.map_err(|e| format!("{}: {}", f().into(), e))
    }
}

fn example() -> Result<(), String> {
    let content = std::fs::read_to_string("config.json")
        .with_context(|| "Failed to read config")?;
    Ok(())
}

6.3 Builder Pattern

struct HttpClient {
    base_url: String,
    timeout: std::time::Duration,
    headers: Vec<(String, String)>,
    retry_count: u32,
}

struct HttpClientBuilder {
    base_url: Option<String>,
    timeout: std::time::Duration,
    headers: Vec<(String, String)>,
    retry_count: u32,
}

impl HttpClientBuilder {
    fn new() -> Self {
        Self {
            base_url: None,
            timeout: std::time::Duration::from_secs(30),
            headers: Vec::new(),
            retry_count: 3,
        }
    }

    fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    fn timeout(mut self, duration: std::time::Duration) -> Self {
        self.timeout = duration;
        self
    }

    fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((key.into(), value.into()));
        self
    }

    fn retry_count(mut self, count: u32) -> Self {
        self.retry_count = count;
        self
    }

    fn build(self) -> Result<HttpClient, String> {
        Ok(HttpClient {
            base_url: self.base_url.ok_or("base_url is required")?,
            timeout: self.timeout,
            headers: self.headers,
            retry_count: self.retry_count,
        })
    }
}

fn main() {
    let client = HttpClientBuilder::new()
        .base_url("https://api.example.com")
        .timeout(std::time::Duration::from_secs(10))
        .header("User-Agent", "MyApp/1.0")
        .retry_count(5)
        .build()
        .unwrap();
}

6.4 Type State Pattern

use std::marker::PhantomData;

// States
struct Created;
struct Connected;
struct Authenticated;

struct Database<State = Created> {
    connection_string: String,
    _state: PhantomData<State>,
}

impl Database<Created> {
    fn new(connection_string: String) -> Self {
        Database {
            connection_string,
            _state: PhantomData,
        }
    }

    fn connect(self) -> Result<Database<Connected>, String> {
        println!("Connecting to {}", self.connection_string);
        Ok(Database {
            connection_string: self.connection_string,
            _state: PhantomData,
        })
    }
}

impl Database<Connected> {
    fn authenticate(self, password: &str) -> Result<Database<Authenticated>, String> {
        if password == "secret" {
            Ok(Database {
                connection_string: self.connection_string,
                _state: PhantomData,
            })
        } else {
            Err("Authentication failed".to_string())
        }
    }
}

impl Database<Authenticated> {
    fn query(&self, sql: &str) -> Result<Vec<String>, String> {
        println!("Executing: {}", sql);
        Ok(vec!["result1".to_string(), "result2".to_string()])
    }
}

fn main() {
    let db = Database::new("localhost:5432".to_string())
        .connect()
        .unwrap()
        .authenticate("secret")
        .unwrap();

    db.query("SELECT * FROM users").unwrap();

    // Won't compile: can't query before authentication!
    // let db = Database::new("localhost:5432".to_string());
    // db.query("SELECT * FROM users");
}

6.5 Strategy Pattern

trait CompressionStrategy {
    fn compress(&self, data: &[u8]) -> Vec<u8>;
    fn decompress(&self, data: &[u8]) -> Vec<u8>;
}

struct GzipCompression;
struct ZstdCompression;

impl CompressionStrategy for GzipCompression {
    fn compress(&self, data: &[u8]) -> Vec<u8> {
        println!("Compressing with gzip");
        data.to_vec() // Simplified
    }

    fn decompress(&self, data: &[u8]) -> Vec<u8> {
        println!("Decompressing with gzip");
        data.to_vec()
    }
}

impl CompressionStrategy for ZstdCompression {
    fn compress(&self, data: &[u8]) -> Vec<u8> {
        println!("Compressing with zstd");
        data.to_vec()
    }

    fn decompress(&self, data: &[u8]) -> Vec<u8> {
        println!("Decompressing with zstd");
        data.to_vec()
    }
}

struct Compressor {
    strategy: Box<dyn CompressionStrategy>,
}

impl Compressor {
    fn new(strategy: Box<dyn CompressionStrategy>) -> Self {
        Compressor { strategy }
    }

    fn compress(&self, data: &[u8]) -> Vec<u8> {
        self.strategy.compress(data)
    }
}

fn main() {
    let data = b"Hello, World!";

    let compressor = Compressor::new(Box::new(GzipCompression));
    compressor.compress(data);

    let compressor = Compressor::new(Box::new(ZstdCompression));
    compressor.compress(data);
}

6.6 Command Pattern

trait Command {
    fn execute(&mut self) -> Result<(), String>;
    fn undo(&mut self) -> Result<(), String>;
}

struct Counter {
    value: i32,
}

struct IncrementCommand {
    counter: *mut Counter,
    amount: i32,
}

impl Command for IncrementCommand {
    fn execute(&mut self) -> Result<(), String> {
        unsafe {
            (*self.counter).value += self.amount;
        }
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        unsafe {
            (*self.counter).value -= self.amount;
        }
        Ok(())
    }
}

struct CommandHistory {
    commands: Vec<Box<dyn Command>>,
    position: usize,
}

impl CommandHistory {
    fn new() -> Self {
        CommandHistory {
            commands: Vec::new(),
            position: 0,
        }
    }

    fn execute(&mut self, mut command: Box<dyn Command>) -> Result<(), String> {
        command.execute()?;
        self.commands.truncate(self.position);
        self.commands.push(command);
        self.position += 1;
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        if self.position == 0 {
            return Err("Nothing to undo".to_string());
        }
        self.position -= 1;
        self.commands[self.position].undo()
    }
}

6.7 Visitor Pattern

trait Visitor {
    fn visit_file(&mut self, file: &File);
    fn visit_directory(&mut self, dir: &Directory);
}

trait Visitable {
    fn accept(&self, visitor: &mut dyn Visitor);
}

struct File {
    name: String,
    size: u64,
}

struct Directory {
    name: String,
    children: Vec<Box<dyn Visitable>>,
}

impl Visitable for File {
    fn accept(&self, visitor: &mut dyn Visitor) {
        visitor.visit_file(self);
    }
}

impl Visitable for Directory {
    fn accept(&self, visitor: &mut dyn Visitor) {
        visitor.visit_directory(self);
        for child in &self.children {
            child.accept(visitor);
        }
    }
}

struct SizeCalculator {
    total_size: u64,
}

impl Visitor for SizeCalculator {
    fn visit_file(&mut self, file: &File) {
        self.total_size += file.size;
    }

    fn visit_directory(&mut self, _dir: &Directory) {
        // Directory itself has no size
    }
}

6.8 Dependency Injection

trait Logger {
    fn log(&self, message: &str);
}

struct ConsoleLogger;
struct FileLogger {
    path: String,
}

impl Logger for ConsoleLogger {
    fn log(&self, message: &str) {
        println!("[LOG] {}", message);
    }
}

impl Logger for FileLogger {
    fn log(&self, message: &str) {
        println!("[FILE] Writing to {}: {}", self.path, message);
    }
}

struct UserService<L: Logger> {
    logger: L,
}

impl<L: Logger> UserService<L> {
    fn new(logger: L) -> Self {
        UserService { logger }
    }

    fn create_user(&self, name: &str) {
        self.logger.log(&format!("Creating user: {}", name));
        // Create user logic
    }
}

fn main() {
    let console_service = UserService::new(ConsoleLogger);
    console_service.create_user("Alice");

    let file_service = UserService::new(FileLogger {
        path: "app.log".to_string(),
    });
    file_service.create_user("Bob");
}

6.9 Option and Result Combinators

fn combinator_examples() {
    // map: transform the value
    let value = Some(5).map(|x| x * 2);  // Some(10)

    // and_then: chain operations
    let result = Some(5)
        .and_then(|x| if x > 0 { Some(x * 2) } else { None });

    // or: provide alternative
    let value = None.or(Some(42));  // Some(42)

    // unwrap_or: default value
    let value = None.unwrap_or(0);  // 0

    // map_or: transform with default
    let value = Some("hello").map_or(0, |s| s.len());  // 5

    // ok_or: convert Option to Result
    let result: Result<i32, &str> = Some(42).ok_or("not found");
}

fn result_combinators() -> Result<i32, String> {
    // Chaining with ?
    let value = parse_number("42")?;
    let doubled = multiply_by_two(value)?;
    Ok(doubled)
}

fn parse_number(s: &str) -> Result<i32, String> {
    s.parse().map_err(|e| format!("Parse error: {}", e))
}

fn multiply_by_two(n: i32) -> Result<i32, String> {
    Ok(n * 2)
}

6.10 Chapter Summary

Key Takeaways

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.