From: Paolo Bonzini <pbonzini@redhat.com>
To: qemu-devel@nongnu.org
Cc: armbru@redhat.com, marcandre.lureau@redhat.com, qemu-rust@nongnu.org
Subject: [PATCH 02/19] rust/util: use anyhow's native chaining capabilities
Date: Fri, 10 Oct 2025 17:09:47 +0200 [thread overview]
Message-ID: <20251010151006.791038-3-pbonzini@redhat.com> (raw)
In-Reply-To: <20251010151006.791038-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 | 139 ++++++++++++++---------------------------
1 file changed, 46 insertions(+), 93 deletions(-)
diff --git a/rust/util/src/error.rs b/rust/util/src/error.rs
index 20b8e7d5af5..bdbf2634170 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,104 +50,65 @@
#[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();
+ Error {
+ 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)]
pub fn format(args: fmt::Arguments) -> Self {
if let Some(msg) = args.as_str() {
- Self::from(msg)
+ Self::new(anyhow::Error::msg(msg))
} else {
let msg = std::fmt::format(args);
- Self::from(msg)
+ Self::new(anyhow::Error::msg(msg))
}
}
@@ -155,9 +117,10 @@ pub fn format(args: fmt::Arguments) -> Self {
#[track_caller]
pub fn with_error(msg: impl Into<Cow<'static, str>>, cause: impl Into<anyhow::Error>) -> Self {
let location = panic::Location::caller();
+ let msg: Cow<'static, str> = msg.into();
+ let cause: anyhow::Error = cause.into();
Error {
- msg: Some(msg.into()),
- cause: Some(cause.into()),
+ cause: cause.context(msg),
file: location.file(),
line: location.line(),
}
@@ -326,8 +289,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,
}
@@ -370,8 +332,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);
}
};
}
@@ -410,19 +372,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!(
@@ -439,7 +392,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");
@@ -456,7 +409,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.0
next prev parent reply other threads:[~2025-10-10 15:11 UTC|newest]
Thread overview: 21+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-10-10 15:09 [PATCH 00/19] rust: QObject and QAPI bindings Paolo Bonzini
2025-10-10 15:09 ` [PATCH 01/19] util: add ensure macro Paolo Bonzini
2025-10-10 15:09 ` Paolo Bonzini [this message]
2025-10-10 15:09 ` [PATCH 03/19] rust: do not add qemuutil to Rust crates Paolo Bonzini
2025-10-10 15:09 ` [PATCH 04/19] rust/qobject: add basic bindings Paolo Bonzini
2025-10-10 15:09 ` [PATCH 05/19] subprojects: add serde Paolo Bonzini
2025-10-10 15:09 ` [PATCH 06/19] rust/qobject: add Serialize implementation Paolo Bonzini
2025-10-10 15:09 ` [PATCH 07/19] rust/qobject: add Serializer (to_qobject) implementation Paolo Bonzini
2025-10-10 15:09 ` [PATCH 08/19] rust/qobject: add Deserialize implementation Paolo Bonzini
2025-10-10 15:09 ` [PATCH 09/19] rust/qobject: add Deserializer (from_qobject) implementation Paolo Bonzini
2025-10-10 15:09 ` [PATCH 10/19] rust/util: replace Error::err_or_unit/err_or_else with Error::with_errp Paolo Bonzini
2025-10-10 15:09 ` [PATCH 11/19] rust/qobject: add from/to JSON bindings for QObject Paolo Bonzini
2025-10-10 15:09 ` [PATCH 12/19] rust/qobject: add Display/Debug Paolo Bonzini
2025-10-10 15:09 ` [PATCH 13/19] scripts/qapi: add QAPISchemaIfCond.rsgen() Paolo Bonzini
2025-10-10 15:09 ` [PATCH 14/19] scripts/qapi: generate high-level Rust bindings Paolo Bonzini
2025-10-10 15:10 ` [PATCH 15/19] scripts/qapi: add serde attributes Paolo Bonzini
2025-10-10 15:10 ` [PATCH 16/19] scripts/qapi: strip trailing whitespaces Paolo Bonzini
2025-10-10 15:10 ` [PATCH 17/19] scripts/rustc_args: add --no-strict-cfg Paolo Bonzini
2025-10-10 15:10 ` [PATCH 18/19] rust/util: build QAPI types Paolo Bonzini
2025-10-10 15:10 ` [PATCH 19/19] rust/tests: QAPI integration tests Paolo Bonzini
2025-10-30 17:13 ` [PATCH 00/19] rust: QObject and QAPI bindings Paolo Bonzini
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=20251010151006.791038-3-pbonzini@redhat.com \
--to=pbonzini@redhat.com \
--cc=armbru@redhat.com \
--cc=marcandre.lureau@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).