From: Paolo Bonzini <pbonzini@redhat.com>
To: qemu-devel@nongnu.org
Cc: qemu-rust@nongnu.org
Subject: [PATCH 2/4] rust/util: use anyhow's native chaining capabilities
Date: Fri, 31 Oct 2025 16:25:37 +0100 [thread overview]
Message-ID: <20251031152540.293293-3-pbonzini@redhat.com> (raw)
In-Reply-To: <20251031152540.293293-1-pbonzini@redhat.com>
This simplifies conversions, making it possible to convert any error
into a QEMU util::Error with ".into()" (and therefore with "?").
The cost is having a separate constructor for when the error is a simple
string, but that is made easier by the ensure! macro. If necessary,
another macro similar to "anyhow!" can be returned, but for now there
is no need for that.
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
---
rust/util/src/error.rs | 160 +++++++++++++++--------------------------
1 file changed, 59 insertions(+), 101 deletions(-)
diff --git a/rust/util/src/error.rs b/rust/util/src/error.rs
index 2a57c7fd5fd..11b574ca593 100644
--- a/rust/util/src/error.rs
+++ b/rust/util/src/error.rs
@@ -38,6 +38,7 @@
borrow::Cow,
ffi::{c_char, c_int, c_void, CStr},
fmt::{self, Display},
+ ops::Deref,
panic, ptr,
};
@@ -49,118 +50,85 @@
#[derive(Debug)]
pub struct Error {
- msg: Option<Cow<'static, str>>,
- /// Appends the print string of the error to the msg if not None
- cause: Option<anyhow::Error>,
+ cause: anyhow::Error,
file: &'static str,
line: u32,
}
-impl std::error::Error for Error {
- fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
- self.cause.as_ref().map(AsRef::as_ref)
- }
+impl Deref for Error {
+ type Target = anyhow::Error;
- #[allow(deprecated)]
- fn description(&self) -> &str {
- self.msg
- .as_deref()
- .or_else(|| self.cause.as_deref().map(std::error::Error::description))
- .expect("no message nor cause?")
+ fn deref(&self) -> &Self::Target {
+ &self.cause
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- let mut prefix = "";
- if let Some(ref msg) = self.msg {
- write!(f, "{msg}")?;
- prefix = ": ";
- }
- if let Some(ref cause) = self.cause {
- write!(f, "{prefix}{cause}")?;
- } else if prefix.is_empty() {
- panic!("no message nor cause?");
- }
- Ok(())
+ Display::fmt(&format_args!("{:#}", self.cause), f)
}
}
-impl From<Cow<'static, str>> for Error {
+impl<E> From<E> for Error
+where
+ anyhow::Error: From<E>,
+{
#[track_caller]
- fn from(msg: Cow<'static, str>) -> Self {
- let location = panic::Location::caller();
- Error {
- msg: Some(msg),
- cause: None,
- file: location.file(),
- line: location.line(),
- }
- }
-}
-
-impl From<String> for Error {
- #[track_caller]
- fn from(msg: String) -> Self {
- let location = panic::Location::caller();
- Error {
- msg: Some(Cow::Owned(msg)),
- cause: None,
- file: location.file(),
- line: location.line(),
- }
- }
-}
-
-impl From<&'static str> for Error {
- #[track_caller]
- fn from(msg: &'static str) -> Self {
- let location = panic::Location::caller();
- Error {
- msg: Some(Cow::Borrowed(msg)),
- cause: None,
- file: location.file(),
- line: location.line(),
- }
- }
-}
-
-impl From<anyhow::Error> for Error {
- #[track_caller]
- fn from(error: anyhow::Error) -> Self {
- let location = panic::Location::caller();
- Error {
- msg: None,
- cause: Some(error),
- file: location.file(),
- line: location.line(),
- }
+ fn from(src: E) -> Self {
+ Self::new(anyhow::Error::from(src))
}
}
impl Error {
+ /// Create a new error from an [`anyhow::Error`].
+ ///
+ /// This wraps the error with QEMU's location tracking information.
+ /// Most code should use the `?` operator instead of calling this directly.
+ #[track_caller]
+ pub fn new(cause: anyhow::Error) -> Self {
+ let location = panic::Location::caller();
+ Self {
+ cause,
+ file: location.file(),
+ line: location.line(),
+ }
+ }
+
+ /// Create a new error from a string message.
+ ///
+ /// This is a convenience wrapper around [`Error::new`] for simple string
+ /// errors. Most code should use the [`ensure!`](crate::ensure) macro
+ /// instead of calling this directly.
+ #[track_caller]
+ pub fn msg(src: impl Into<Cow<'static, str>>) -> Self {
+ Self::new(anyhow::Error::msg(src.into()))
+ }
+
#[track_caller]
#[doc(hidden)]
+ #[inline(always)]
pub fn format(args: fmt::Arguments) -> Self {
- if let Some(msg) = args.as_str() {
- Self::from(msg)
- } else {
- let msg = fmt::format(args);
- Self::from(msg)
- }
+ // anyhow::Error::msg will allocate anyway, might as well let fmt::format doit.
+ let msg = fmt::format(args);
+ Self::new(anyhow::Error::msg(msg))
}
/// Create a new error, prepending `msg` to the
/// description of `cause`
#[track_caller]
pub fn with_error(msg: impl Into<Cow<'static, str>>, cause: impl Into<anyhow::Error>) -> Self {
- let location = panic::Location::caller();
- Error {
- msg: Some(msg.into()),
- cause: Some(cause.into()),
- file: location.file(),
- line: location.line(),
+ fn do_with_error(
+ msg: Cow<'static, str>,
+ cause: anyhow::Error,
+ location: &'static panic::Location<'static>,
+ ) -> Error {
+ Error {
+ cause: cause.context(msg),
+ file: location.file(),
+ line: location.line(),
+ }
}
+ do_with_error(msg.into(), cause.into(), panic::Location::caller())
}
/// Consume a result, returning `false` if it is an error and
@@ -326,8 +294,7 @@ unsafe fn cloned_from_foreign(c_error: *const bindings::Error) -> Self {
};
Error {
- msg: FromForeign::cloned_from_foreign(error.msg),
- cause: None,
+ cause: anyhow::Error::msg(String::cloned_from_foreign(error.msg)),
file: file.unwrap(),
line: error.line as u32,
}
@@ -376,8 +343,8 @@ macro_rules! ensure {
};
($cond:expr, $err:expr $(,)?) => {
if !$cond {
- let s = ::std::borrow::Cow::<'static, str>::from($err);
- return $crate::Result::Err(s.into());
+ let e = $crate::Error::msg($err);
+ return $crate::Result::Err(e);
}
};
}
@@ -416,19 +383,10 @@ unsafe fn error_get_pretty<'a>(local_err: *mut bindings::Error) -> &'a CStr {
unsafe { CStr::from_ptr(bindings::error_get_pretty(local_err)) }
}
- #[test]
- #[allow(deprecated)]
- fn test_description() {
- use std::error::Error;
-
- assert_eq!(super::Error::from("msg").description(), "msg");
- assert_eq!(super::Error::from("msg".to_owned()).description(), "msg");
- }
-
#[test]
fn test_display() {
- assert_eq!(&*format!("{}", Error::from("msg")), "msg");
- assert_eq!(&*format!("{}", Error::from("msg".to_owned())), "msg");
+ assert_eq!(&*format!("{}", Error::msg("msg")), "msg");
+ assert_eq!(&*format!("{}", Error::msg("msg".to_owned())), "msg");
assert_eq!(&*format!("{}", Error::from(anyhow!("msg"))), "msg");
assert_eq!(
@@ -445,7 +403,7 @@ fn test_bool_or_propagate() {
assert!(Error::bool_or_propagate(Ok(()), &mut local_err));
assert_eq!(local_err, ptr::null_mut());
- let my_err = Error::from("msg");
+ let my_err = Error::msg("msg");
assert!(!Error::bool_or_propagate(Err(my_err), &mut local_err));
assert_ne!(local_err, ptr::null_mut());
assert_eq!(error_get_pretty(local_err), c"msg");
@@ -462,7 +420,7 @@ fn test_ptr_or_propagate() {
assert_eq!(String::from_foreign(ret), "abc");
assert_eq!(local_err, ptr::null_mut());
- let my_err = Error::from("msg");
+ let my_err = Error::msg("msg");
assert_eq!(
Error::ptr_or_propagate(Err::<String, _>(my_err), &mut local_err),
ptr::null_mut()
--
2.51.1
next prev parent reply other threads:[~2025-10-31 15:27 UTC|newest]
Thread overview: 9+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-10-31 15:25 [PATCH 0/4] rust: improvements to errors Paolo Bonzini
2025-10-31 15:25 ` [PATCH 1/4] rust/util: add ensure macro Paolo Bonzini
2025-11-04 15:17 ` Zhao Liu
2025-10-31 15:25 ` Paolo Bonzini [this message]
2025-11-04 15:31 ` [PATCH 2/4] rust/util: use anyhow's native chaining capabilities Zhao Liu
2025-10-31 15:25 ` [PATCH 3/4] rust/util: replace Error::err_or_unit/err_or_else with Error::with_errp Paolo Bonzini
2025-11-04 15:44 ` Zhao Liu
2025-10-31 15:25 ` [PATCH 4/4] rust: pull error_fatal out of SysbusDeviceMethods::sysbus_realize Paolo Bonzini
2025-11-04 15:47 ` Zhao Liu
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20251031152540.293293-3-pbonzini@redhat.com \
--to=pbonzini@redhat.com \
--cc=qemu-devel@nongnu.org \
--cc=qemu-rust@nongnu.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).