33 ms·
My favorite thing in rust is the error handling and propagation. Using JS for comparison. Example, this code in JS function decode(path){ try {
by vatotemking 9y ago
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 (...)
...
}
- steveklabnik 9y agoDon't forget that try! turned into ? so that's now parse(path)? !
- vatotemking 9y agoYes but I still prefer try! as its easier to see (personal preference)
- colejohnson66 9y agoWhat’s the point of catching and rethrowing?
- vatotemking 9y agoWhen your inside a module and you want the app using your module to catch the exception.