File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -96,6 +96,45 @@ impl<'a> PanicHookInfo<'a> {
96
96
self . payload
97
97
}
98
98
99
+ /// Returns the payload associated with the panic, if it is a string.
100
+ ///
101
+ /// This returns the payload if it is of type `&'static str` or `String`.
102
+ ///
103
+ /// A invocation of the `panic!()` macro in Rust 2021 or later will always result in a
104
+ /// panic payload where `payload_as_str` returns `Some`.
105
+ ///
106
+ /// Only an invocation of [`panic_any`]
107
+ /// (or, in Rust 2018 and earlier, `panic!(x)` where `x` is something other than a string)
108
+ /// can result in a panic payload where `payload_as_str` returns `None`.
109
+ ///
110
+ /// # Example
111
+ ///
112
+ /// ```should_panic
113
+ /// #![feature(panic_payload_as_str)]
114
+ ///
115
+ /// std::panic::set_hook(Box::new(|panic_info| {
116
+ /// if let Some(s) = panic_info.payload_as_str() {
117
+ /// println!("panic occurred: {s:?}");
118
+ /// } else {
119
+ /// println!("panic occurred");
120
+ /// }
121
+ /// }));
122
+ ///
123
+ /// panic!("Normal panic");
124
+ /// ```
125
+ #[ must_use]
126
+ #[ inline]
127
+ #[ unstable( feature = "panic_payload_as_str" , issue = "125175" ) ]
128
+ pub fn payload_as_str ( & self ) -> Option < & str > {
129
+ if let Some ( s) = self . payload . downcast_ref :: < & str > ( ) {
130
+ Some ( s)
131
+ } else if let Some ( s) = self . payload . downcast_ref :: < String > ( ) {
132
+ Some ( s)
133
+ } else {
134
+ None
135
+ }
136
+ }
137
+
99
138
/// Returns information about the location from which the panic originated,
100
139
/// if available.
101
140
///
You can’t perform that action at this time.
0 commit comments