#rest

errors_rust

Just a simple library for error mapping

1 unstable release

0.1.0 Jul 27, 2019

#245 in #rest

Custom license

17KB
62 lines

Errors Rust

This project is to map errors using a wrapper, this is useful when you need to map errors between layers on an API rest to avoid having to use panic or specific errors from a framework.

How to use it

You just need to import this project into yours and use like this:

use errors_rust::errors::generic::{RustError, RustErrorParams};

struct Test {}

impl Test {
    pub fn method_1(some_param: Option<bool>) -> Result<bool, RustError> {
        if some_param.is_none() {
            return Err(RustError::from_string("Error Method 1"));
        }
        Ok(some_param.unwrap())
    }
    pub fn method_2(some_param: Option<bool>) -> Result<bool, RustError> {
        if some_param.is_none() {
            return Err(RustError::from_params(RustErrorParams{
                code: Some(10),
                description: Some(String::from("Error Method 2")),
                message: Some(String::from("Message From Error Method 2"))
            }));
        }
        Ok(some_param.unwrap())
    }
    pub fn method_3(some_param: Option<bool>) -> Result<bool, RustError> {
        if some_param.is_none() {
            return Err(RustError::new(Some(10),
                                      Some(String::from("Message From Error Method 3")),
                                      Some(String::from("Error Method 3"))));
        }
        Ok(some_param.unwrap())
    }
}

fn main() {
    let mut result = Test::method_1(None);
    if result.is_err() {
        let rust_error = result.unwrap_err();
        println!("Error Code: {} Error Description: {} Error Message {}", rust_error.code, rust_error.description, rust_error.message);
    }
    result = Test::method_2(None);
    if result.is_err() {
        let rust_error = result.unwrap_err();
        println!("Error Code: {} Error Description: {} Error Message {}", rust_error.code, rust_error.description, rust_error.message);
    }
    result = Test::method_3(None);
    if result.is_err() {
        let rust_error = result.unwrap_err();
        println!("Error Code: {} Error Description: {} Error Message {}", rust_error.code, rust_error.description, rust_error.message);
    }
}

Available on crates.io

You can use this dependency on your Cargo.toml like this:

[dependencies.errors_rust]
version = "0.1.0"

Dependencies

~0.7–1.6MB
~34K SLoC