Skip to content

Refactor explicit production of errors

Alex Crichton requested to merge alexcrichton/gnome-class:errors into master

I was reading over the gnome-class macro crate recently and I was having a difficult time getting up to speed on the error handling of the crate as it was using a number of patterns I hadn't seen before. I was also wondering how only one Span was necessary to create an error when multi-token spans were needed sometimes, which led me in the end to start a refactor here.

The first point of refactoring was to ensure that multi-token errors were handled. Although the syn crate has a Spanned trait it doesn't actually work on stable Rust, so the errors coming out of gnome-class today weren't compatible with being spanned over multiple tokens. I added a convenience API in https://github.com/dtolnay/syn/pull/538 and have started using that here to construct syn Error instances.

Next I opted to lift similar error handling from the failure crate here as well. This was primarily the bail! macro as well as the format_err! macro, used to quickly return and create errors with formatted messages.

Using this macro I was able to replace most of the support traits in src/errors.rs with local error handling and/or various other idioms. Afterwards the crate (to me at least) feels much more idiomatic in terms of error handling where ? is still maximally used, returning an error is easy to do, and there aren't too many traits/methods to discover when learning how to work with errors.

Merge request reports