by thenewwazoo · 7y ago · 0 comments
For example, if your errors are:
enum RispError {
/// Syntax error returning line number and char
SyntaxErr(u32, u32),
/// Parens not balanced; contains number of parens needed
UnbalancedParens(usize),
}
You can impl ToString straight away: impl ToString for RispErr {
fn to_string(&self) -> String {
match self {
RispErr::SyntaxErr(l,c) => format!("syntax error at line {}, col {}", l, c),
RispErr::UnbalancedParens(n) => format!("use your % key more! add {} more paren", n),
}
}
}
Then, when handling the error, you can match do_thing() {
Ok(v) => { ... },
Err(e) => { // TODO handle error
println!(e)
}
}
where do_thing's signature looks like fn do_thing(...) -> Result<T, RispErr>;
It takes the same amount of code, but all your error messages are in the same place, you haven't lost information about them, and refactoring to handle them becomes super easy.(n.b. I dashed this comment off without actually compiling the above, so please forgive any dumb errors =] )
[1] https://doc.rust-lang.org/std/string/trait.ToString.html
http://www.lispworks.com/documentation/HyperSpec/Body/f_cerr...
http://www.lispworks.com/documentation/HyperSpec/Body/m_rst_...
I gotta get to sleep, but will either update the post or add a note in the morning.
And of course, will do this in all future rust projects :D
See here: https://github.com/omarabid/rust-starter/blob/master/src/mai...