macro_rules! err {
(@accum $body:tt $(,)?) => { ... };
(@accum ($($body:tt)*), source($src:expr) $($tail:tt)*) => { ... };
(@accum ($($body:tt)*), msg($format:expr) $($tail:tt)*) => { ... };
(@accum ($($body:tt)*), msg($format:expr, $($args:tt)*) $($tail:tt)*) => { ... };
($builder:expr $(, $($tail:tt)*)? ) => { ... };
}
Expand description
Constructs an Error
, tersely.
This is a shorthand way to use ErrorBuilder
.
The first argument is an Into<ErrorBuilder>
, such as the following:
- an
ErrorKind
enum variant name likeUnauthenticated
. There’s an implicituse ::coded::ErrorKind::*
to allow the bare variant names just within this restrictive scope where you’re unlikely to have conflicts with other identifiers. - an
std::io::Error
as a source, which sets the newError
’sErrorKind
based on thestd::io::Error
. - an
Error
as a source, which similarly copies theErrorKind
. - an existing
ErrorBuilder
, which does not create a new source link.
Following arguments may be of these forms:
msg(...)
, which expands to.msg(format!(...))
. SeeErrorBuilder::msg
.source(...)
, which simply expands to.source($src)
. SeeErrorBuilder::source
.
§Examples
Simplest:
let e = err!(InvalidArgument);
let e = err!(InvalidArgument,); // trailing commas are allowed
assert_eq!(e.kind(), coded::ErrorKind::InvalidArgument);
Constructing with a fixed error variant name:
let input = "a12";
let src = i32::from_str_radix(input, 10).unwrap_err();
let e = err!(InvalidArgument, source(src.clone()), msg("bad argument {:?}", input));
// The line above is equivalent to:
let e2 = ::coded::ErrorBuilder::from(::coded::ErrorKind::InvalidArgument)
.source(src.clone())
.msg(format!("bad argument {:?}", input))
.build();
assert_eq!(e.kind(), coded::ErrorKind::InvalidArgument);
assert_eq!(e.source().unwrap().downcast_ref::<ParseIntError>().unwrap(), &src);
Constructing from an std::io::Error
:
let e = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let e = err!(e, msg("path {} not found", "foo"));
assert_eq!(e.kind(), coded::ErrorKind::NotFound);