0Pricing
Learn Rust Coding · Lección

Gestión sólida de errores con `Result`

Implemente una gestión idiomática de errores mediante el enum `Result`, el operador `?` y tipos de error personalizados para crear aplicaciones resistentes.

Gestión sólida de errores con `Result` es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 3 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Handling Errors in Rust

Errors are a part of programming. In Rust, we distinguish between two main types: recoverable and unrecoverable errors.

  • Unrecoverable errors usually signal bugs, causing the program to stop with panic!.
  • Recoverable errors mean something went wrong but can be handled, like a file not found.

Rust helps you deal with recoverable errors gracefully.

`panic!` vs `Result`

When an unrecoverable error occurs, Rust calls the panic! macro. This unwinds the stack and exits your program, usually printing an error message.

For recoverable errors, Rust uses the Result enum. This enum tells you if an operation succeeded (Ok) or failed (Err), letting your program decide what to do next.

The `Result` Enum

The Result enum is defined conceptually as:

enum Result<T, E> {
  Ok(T),
  Err(E),
}

  • T represents the type of value returned on success.
  • E represents the type of error returned on failure.

It's a powerful way to explicitly state that a function might fail.

Matching on `Result`

The most common way to handle a Result is using a match expression. This allows you to execute different code blocks based on whether the Result is Ok or Err.

Try running this example that attempts to parse a number:

fn parse_and_add(text: &str) -> Result<i32, std::num::ParseIntError> {
    text.parse::<i32>()
}

fn main() {
    let num_str = "123";
    let result = parse_and_add(num_str);

    match result {
        Ok(num) => println!("Parsed number: {}", num),
        Err(e) => println!("Error parsing: {}", e),
    }

    let bad_str = "abc";
    let bad_result = parse_and_add(bad_str);

    match bad_result {
        Ok(num) => println!("Parsed number: {}", num),
        Err(e) => println!("Error parsing: {}", e),
    }
}

Unwrapping Results (Carefully!)

Sometimes you might be certain an operation won't fail, or you want your program to crash if it does. Methods like unwrap() and expect() extract the Ok value.

  • unwrap(): Returns the Ok value or panics if it's Err.
  • expect("message"): Same as unwrap() but lets you provide a custom panic message.

Use these sparingly, mainly in tests or when failure is truly unrecoverable.

Introducing the `?` Operator

Writing match statements for every Result can get repetitive. The ? operator provides a concise shortcut for error propagation.

When placed after an expression that returns a Result, ? does two things:

  • If the Result is Err, it immediately returns the Err from the current function.
  • If the Result is Ok, it unwraps the Ok value and continues execution.

`?` Operator in Action

The ? operator makes functions that might fail much cleaner to write. Remember, the function using ? must itself return a Result (or Option).

Observe how ? simplifies error handling in this file reading example:

use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?; // Propagates error if file not found
    let mut s = String::new();
    f.read_to_string(&mut s)?; // Propagates error if read fails
    Ok(s)
}

fn main() {
    // Create a dummy file for the example to work
    // In a real scenario, this file might not exist
    std::fs::write("hello.txt", "CoddyKit User").unwrap();

    match read_username_from_file() {
        Ok(username) => println!("Username: {}", username),
        Err(e) => println!("Error reading username: {}", e),
    }

    // Clean up the dummy file
    std::fs::remove_file("hello.txt").unwrap();
}

Custom Error Types

Sometimes, built-in error types aren't specific enough. You can define your own custom error types using enums to represent different failure modes of your application.

This makes your error messages clearer and allows callers to handle specific errors differently.

A common pattern is to create an enum that lists all possible errors a function or module can produce.

Making `?` Work with Custom Errors

For the ? operator to automatically convert a lower-level error (like io::Error) into your custom error type, your custom error enum must implement the From trait for that lower-level error.

This tells Rust how to convert one error type into another, making error propagation seamless.

use std::io;
use std::fs::File;
use std::io::Read;

#[derive(Debug)]
enum MyError {
    Io(io::Error),
    Parse(std::num::ParseIntError)
}

impl From<io::Error> for MyError {
    fn from(error: io::Error) -> Self {
        MyError::Io(error)
    }
}

impl From<std::num::ParseIntError> for MyError {
    fn from(error: std::num::ParseIntError) -> Self {
        MyError::Parse(error)
    }
}

fn read_config(path: &str) -> Result<i32, MyError> {
    let mut file = File::open(path)?; // io::Error converted to MyError::Io
    let mut contents = String::new();
    file.read_to_string(&mut contents)?; // io::Error converted to MyError::Io
    let value = contents.trim().parse::<i32>()?; // ParseIntError converted to MyError::Parse
    Ok(value)
}

fn main() {
    // Create a dummy file for the example
    std::fs::write("config.txt", "123").unwrap();

    match read_config("config.txt") {
        Ok(val) => println!("Config value: {}", val),
        Err(e) => println!("Failed to read config: {:?}", e),
    }

    std::fs::remove_file("config.txt").unwrap(); // Clean up

    // Example with a non-existent file
    match read_config("non_existent.txt") {
        Ok(val) => println!("Config value: {}", val),
        Err(e) => println!("Failed to read config: {:?}", e),
    }
}

Check Your Understanding

Consider the following Rust code snippet. What will be the output if the file data.txt does NOT exist?

Recap: Robust Error Handling

You've mastered robust error handling in Rust!

  • Result Enum: Distinguishes between Ok(T) for success and Err(E) for failure.
  • match: The fundamental way to handle Result variants.
  • ? Operator: A powerful shortcut for propagating Err values up the call stack.
  • Custom Errors: Define your own error types using enums for clarity and specific handling.
  • From Trait: Enables seamless conversion of lower-level errors into your custom error types when using ?.

Next, explore advanced type system features!

Preguntas frecuentes

¿La lección «Gestión sólida de errores con `Result`» es gratis?

Sí — el texto completo de «Gestión sólida de errores con `Result`» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 3 lecciones en total.

¿Qué aprenderé en «Gestión sólida de errores con `Result`»?

Implemente una gestión idiomática de errores mediante el enum `Result`, el operador `?` y tipos de error personalizados para crear aplicaciones resistentes. Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 3.

¿Cuánto tiempo toma la lección «Gestión sólida de errores con `Result`»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Organización del código con módulos
  2. Gestión de dependencias con crates
  3. Gestión sólida de errores con `Result`
← Volver a Learn Rust Coding