error-chain
error-chain copied to clipboard
log feature - support use of the log crate
Hi,
This pull request allows the use of the log crate with error chain. It extends Result and Error with functions to log the errors and their causes. Please let me know if you would be willing to accept it. Example:
...
let mut req = cl.get(&*url)
.send()
.chain_err(|| GetUrl(url.to_string(), "Failed to read".to_string()))
.loge()?;
...
This will print the following given a badurl:
ERROR|rget::errors|Unable open url: 'badurl' : 'Failed to read'
ERROR|rget::errors| caused by: relative URL without a base
Features:
- Zero-cost: is enabled only by the
logfeature. If the feature is not used there is no cost. - Great effort was made to maintain full backwards compatibility, even if the feature is enabled.
- All tests pass with the feature disabled or enabled (e.g.
cargo test --features log && cargo test) - Supports
error!,warn!,info!,debug!,trace!with the chainable functionsloge(),logw(),logi(),logd(),logt() - The user can choose the logger front end for logging, the feature supports any logger that implements the log crate.
Missing:
- More tests for the log feature
- Documentation
- Provide a way to change the "caused by" string used to display the chained errors
- Add
cargo test --features logto travis
NOTE: travis test with rust 1.10 fails because 1.10 does not support #[cfg(feature(...)] for conditional macro execution. I don't think there is any need to spend time on this, since 1.11 works OK. If you agree, maybe the travis minimum version should be updated to rust 1.11
Can't this be put into a separate crate? This would be the better solution IMO as the feature is mostly orthogonal.
@est31 It can't be put in a separate crate, because the log.. functions are intended to log both the acual error and the chain of errors (the causes). If we did it in a separate crate there would be no access to the internal error object that contains all the causes, which is the whole point of logging right at the point of failure (to see the error and its causes).
BTW, one of the reasons for the new failure crate is precisely to solve this problem, and to allow downcasting the error to the internal errors whilst providing access to the causes.