[Rust] Error handling with Enum

We can use Reusltenum to do error handling

type Result<V, E> {
    Err(E),
    Ok(V)
}

 

Example:

// (): empty
// uszie: just return a integre as error for demo
fn error_me(throw: bool) -> Result<(), usize> {
    if throw {
       return Err(7)
    }
    
    return Ok(())
}

fn main() -> Result<(), usize> {
    let value = error_me(false)? // ? will try to unwrap you Err, if it is an Err return Err, if it is not then unwrap the value and return the value
    /**
    // error_me(false)?: the same as following code
    let value = match error_me(false) {
        Err(e) => return Err(e), 
        Ok(v) => v
    }
    */
    
    if error_me(true).is_ok() {
       // never come here, because throw Err
    }
    
    // error_me(true).expect("Program crash, here is why")
    // expect() will panic in case of an Err, printing the provided message
    
    Ok(())
}

 

Using Anyhow library to handle error:

https://github.com/dtolnay/anyhow

Install: cargo add anyhow

 

use anyhow::{Result, anyhow, Context};
use std::path::PathBuf;

fn error_me(throw: bool) -> Result<()> {
    if throw {
       return Err(anyhow!("error when throw is true"));
    }
    
    // Attempt to read a file that doesn't exist, adding context to the error
    std::fs::read(PathBuf::from("/foo")).context("unable to do this")
    
    Ok(())
}

fn main() -> Result<()> {
    let value = error_me(false)? // ? will try to unwrap you Err, if it is an Err return Err, if it is not then unwrap the value and return the value
    /**
    // error_me(false)?: the same as following code
    let value = match error_me(false) {
        Err(e) => return Err(e), 
        Ok(v) => v
    }
    */
    
    if error_me(true).is_ok() {
       // never come here, because throw Err
    }
    
    // error_me(true).expect("Program crash, here is why")
    // expect() will panic in case of an Err, printing the provided message
    
    Ok(())
}

 

posted @ 2024-02-15 16:09  Zhentiw  阅读(2)  评论(0编辑  收藏  举报