Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My favorite thing in rust is the error handling and propagation.

Using JS for comparison.

Example, this code in JS

function decode(path){

    try {

        return parse(path);

    } catch (err){

        throw err; // rethrow

    }
}

Could be compacted into this using try! macro or "?".

pub fn decode(path: &File) -> Result<Image>{

    try!(parse(path))
}

For error propagation, I could easily consume the error of a third-party lib, and convert it into my own using the From trait:

/// Convert std::io::Error to RasterError::Io

impl From<IoError> for RasterError {

    fn from(err: IoError) -> RasterError {

        RasterError::Io(err)

    }
}

Where as in JS, I would have to write a lot of if else if I want to convert a third-party package's error into my own error.

if( error.name === "IoError" ){

    let err = new Error(error);

    err.name = "MyError";

    return err;
} else if (...)

    ...

}


Don't forget that try! turned into ? so that's now

  parse(path)?

!


Yes but I still prefer try! as its easier to see (personal preference)


What’s the point of catching and rethrowing?


When your inside a module and you want the app using your module to catch the exception.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: