Skip to content

Commit a945ca6

Browse files
thiblahutesdroege
authored andcommitted
glib: Add Error::with_domain constructor and code getter
Add a constructor to create errors from a domain quark and code, useful when creating errors with the same domain/code but different messages as we can't get a rust type which implements the `ErrorDomain` in that case. This also adds a code() getter method to retrieve the error code.
1 parent 757579d commit a945ca6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

glib/src/error.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,33 @@ impl Error {
3939
}
4040
}
4141

42+
// rustdoc-stripper-ignore-next
43+
/// Creates an error with supplied error domain quark, code and message.
44+
///
45+
/// This is useful when you need to create an error with the same domain and code
46+
/// as an existing error but with a different message.
47+
///
48+
/// # Examples
49+
///
50+
/// ```ignore
51+
/// let original = Error::new(FileError::Failed, "Original message");
52+
/// let modified = Error::with_domain(
53+
/// original.domain(),
54+
/// original.code(),
55+
/// "Modified message"
56+
/// );
57+
/// ```
58+
#[doc(alias = "g_error_new_literal")]
59+
pub fn with_domain(domain: Quark, code: i32, message: &str) -> Error {
60+
unsafe {
61+
from_glib_full(ffi::g_error_new_literal(
62+
domain.into_glib(),
63+
code,
64+
message.to_glib_none().0,
65+
))
66+
}
67+
}
68+
4269
// rustdoc-stripper-ignore-next
4370
/// Checks if the error domain matches `T`.
4471
pub fn is<T: ErrorDomain>(&self) -> bool {
@@ -51,6 +78,12 @@ impl Error {
5178
unsafe { from_glib(self.inner.domain) }
5279
}
5380

81+
// rustdoc-stripper-ignore-next
82+
/// Returns the error code
83+
pub fn code(&self) -> i32 {
84+
self.inner.code
85+
}
86+
5487
// rustdoc-stripper-ignore-next
5588
/// Checks if the error matches the specified domain and error code.
5689
#[doc(alias = "g_error_matches")]
@@ -329,4 +362,19 @@ mod tests {
329362

330363
assert_eq!(ptr, e2.to_glib_none().0);
331364
}
365+
366+
#[test]
367+
fn test_from_quark() {
368+
let original = Error::new(crate::FileError::Failed, "Original message");
369+
let modified = Error::with_domain(original.domain(), original.code(), "Modified message");
370+
371+
// Should have same domain and code
372+
assert_eq!(original.domain(), modified.domain());
373+
assert_eq!(original.code(), modified.code());
374+
assert!(modified.matches(crate::FileError::Failed));
375+
376+
// But different message
377+
assert_eq!(modified.message(), "Modified message");
378+
assert_ne!(original.message(), modified.message());
379+
}
332380
}

0 commit comments

Comments
 (0)