Pluggable Error Handling


#1

I have read lots of stuff on error handling in Rust, and most of it seems to be focused around returning a Result object. This is fine, of course, but it does not seem very pluggable to me.

I am writing a parser for a piece of XML, and I want the parser to check for errors. But I need it to do different things under different circumstances: parse to the end, summarize all the errors; stop at the first error; and so forth.

My thought was to pass in a function and use this to do call-backs: like an error handler object in java or equivalent. But I’ve not see this done elsewhere and wonder if I am missing something more idiomatic.


#2

Rust used to have this in the standard library, called “condition”: https://doc.rust-lang.org/0.9/std/condition/

Sadly, this was removed in Rust 0.10. I think conditions are great, but exceptions and results are more popular.

On the other hand, you can implement condition system yourself. A good example of condition system in Rust is encoding crate, which allows you to 1. panic, 2. drop, 3. replace with ?, 4. replace with result from custom callback, when you encounter encoding errors. An example of 4 is replacing with XML character entities.

You want to look at EncoderTrap and DecoderTrap enum in encoding crate.


#3

Looks like I am on the right track then! Thanks for the pointer.