panic_as_error/lib.rs
1//! Catching a panic as a value that names where it began.
2//!
3//! A panic turned into an `Err` at the nearest catch lets the caller's own
4//! failure path run: the rollback or cleanup it does on `Err`, which an unwind
5//! would skip. [`caught`] catches a panic in a future, and [`caught_sync`] in
6//! a synchronous call. Each returns a [`Bug`] that holds the text the panic
7//! carried, the operation the work was doing, and the [`SourceLocation`] where
8//! the panic began, which a panic's payload does not hold.
9//!
10//! Work nobody waits for hands its bug to a [`BugSink`] instead, through
11//! [`report`], and an error that holds a bug says so through [`CarriesBug`].
12//! [`locks`] holds the helpers that take a lock whose holder panicked.
13
14use std::any::Any;
15use std::future::Future;
16use std::panic::{catch_unwind, AssertUnwindSafe};
17use std::pin::Pin;
18use std::task::{Context, Poll};
19
20mod location;
21pub mod locks;
22
23pub use location::{catching_operation, SourceLocation};
24
25/// Work that panicked, or that code found wrong without a panic: a bug in it,
26/// not a failure its caller can act on. The caller reports it wherever it
27/// reports its own bugs, and the call that ran the work returns it as its
28/// error.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct Bug {
31 /// What the work was doing, as its caller named it.
32 pub operation: &'static str,
33 /// The text the panic carried ([`panic_message`]).
34 pub message: String,
35 /// Where the bug showed itself: where the panic began, or where the code
36 /// that found the bug made it ([`Bug::new`]). `None` for a panic that began
37 /// outside this crate's catches: one that reached a join uncaught
38 /// ([`bug_of_unlocated`]), or one resumed with
39 /// `std::panic::resume_unwind` from a panic elsewhere.
40 pub location: Option<SourceLocation>,
41 /// Whether the bug showed itself as a panic or code found it.
42 pub kind: BugKind,
43}
44
45impl std::fmt::Display for Bug {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self.kind {
48 BugKind::Panic => write!(f, "{} panicked: {}", self.operation, self.message),
49 BugKind::Found => write!(f, "{} found a bug: {}", self.operation, self.message),
50 }
51 }
52}
53
54impl std::error::Error for Bug {}
55
56/// How a bug showed itself.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum BugKind {
59 /// Work panicked. The process's panic hook saw the panic begin, so an
60 /// app whose own hook reports every panic has reported this one.
61 Panic,
62 /// Code found state its guarantee rules out, without a panic
63 /// ([`Bug::new`]). No hook saw it: whoever the bug reaches reports it.
64 Found,
65}
66
67impl Bug {
68 /// Make the bug that code found in `operation` without a panic, such as
69 /// state a `Drop` finds wrong. Its location is the caller's.
70 #[track_caller]
71 pub fn new(operation: &'static str, message: impl Into<String>) -> Self {
72 Self {
73 operation,
74 message: message.into(),
75 location: Some(SourceLocation::of(std::panic::Location::caller())),
76 kind: BugKind::Found,
77 }
78 }
79}
80
81/// Make the bug for a panic's `payload` when the panic began outside this
82/// crate's catches, so the bug has no location.
83pub fn bug_of_unlocated(operation: &'static str, payload: Box<dyn Any + Send>) -> Bug {
84 bug_of(operation, payload, None)
85}
86
87/// The text a panic carried: what `panic!` and `expect` were given, or a
88/// placeholder for a payload that is not text.
89pub fn panic_message(payload: &(dyn Any + Send)) -> String {
90 if let Some(text) = payload.downcast_ref::<&'static str>() {
91 (*text).to_string()
92 } else if let Some(text) = payload.downcast_ref::<String>() {
93 text.clone()
94 } else {
95 "a panic whose payload is not text".to_string()
96 }
97}
98
99/// Run `work` inline, catching a panic in any of its polls. For one message of
100/// a long-lived loop: the panic fails that message and the loop serves the
101/// next. The runtime can't drop work that runs inline, so a panic is its
102/// only failure.
103///
104/// After a panic, `caught` drops `work` at once, inside a catch of its own, so
105/// a drop that panics on what the first panic left behind does not unwind
106/// into the caller either.
107pub async fn caught<T>(operation: &'static str, work: impl Future<Output = T>) -> Result<T, Bug> {
108 Caught { operation, work: Some(Box::pin(work)) }.await
109}
110
111/// [`caught`] for a synchronous call: an FFI callback, a dedicated thread's
112/// body, a `Drop`. Unwinding out of an `extern "C"` function aborts the
113/// process, so such a function catches here and answers with its own failure
114/// value.
115pub fn caught_sync<T>(operation: &'static str, work: impl FnOnce() -> T) -> Result<T, Bug> {
116 location::catch_located(operation, work).map_err(|(payload, at)| bug_of(operation, payload, at))
117}
118
119/// Where a bug in work nobody waits for goes: a long-lived worker, or work
120/// whose caller stopped waiting for it. The program passes its own crash
121/// reporter.
122pub trait BugSink: Send + Sync {
123 /// Report `bug`, which no caller hears of otherwise.
124 fn report(&self, bug: &Bug);
125}
126
127/// A shared [`BugSink`].
128pub type BugSinkRef = std::sync::Arc<dyn BugSink>;
129
130/// Hand `bug` to `bugs`. When the sink panics too, `report` logs that panic
131/// and stops it there, because nothing above the sink catches it.
132pub fn report(bugs: &dyn BugSink, bug: &Bug) {
133 if let Err(again) = caught_sync("report a bug", || bugs.report(bug)) {
134 tracing::error!(operation = bug.operation, "reporting {bug} panicked: {again}");
135 }
136}
137
138/// An error that may carry a bug: work its call ran panicked, and the call's
139/// error says so. Work nobody waits for reports the bug its error carries, as
140/// it reports its own panic.
141pub trait CarriesBug {
142 /// The bug this error carries, itself or through the failure it keeps.
143 fn bug(&self) -> Option<&Bug>;
144}
145
146impl CarriesBug for Bug {
147 fn bug(&self) -> Option<&Bug> {
148 Some(self)
149 }
150}
151
152/// An I/O error carries the bug it was made from, if any.
153impl CarriesBug for std::io::Error {
154 fn bug(&self) -> Option<&Bug> {
155 self.get_ref()?.downcast_ref::<Bug>()
156 }
157}
158
159/// An error that can't happen carries no bug.
160impl CarriesBug for std::convert::Infallible {
161 fn bug(&self) -> Option<&Bug> {
162 match *self {}
163 }
164}
165
166/// Make the bug for a caught panic's `payload`, which began at `location`.
167/// This function drops the payload inside a catch of its own: a payload whose
168/// `Drop` panics would otherwise unwind out of the helper that caught the
169/// first panic.
170fn bug_of(
171 operation: &'static str,
172 payload: Box<dyn Any + Send>,
173 location: Option<SourceLocation>,
174) -> Bug {
175 let bug =
176 Bug { operation, message: panic_message(payload.as_ref()), location, kind: BugKind::Panic };
177 if bug.location.is_none() {
178 tracing::warn!(
179 operation,
180 "{bug}: the panic began outside this crate's catches, so the bug has no location"
181 );
182 }
183 if let Err(again) = catch_unwind(AssertUnwindSafe(move || drop(payload))) {
184 tracing::error!(
185 operation,
186 "dropping the payload of a panic panicked again: {}",
187 panic_message(again.as_ref())
188 );
189 // This payload's own drop may panic too; leaking it is what keeps
190 // the unwind from reaching the caller.
191 std::mem::forget(again);
192 }
193 bug
194}
195
196struct Caught<F: Future> {
197 operation: &'static str,
198 /// `None` once `work` has finished or panicked.
199 work: Option<Pin<Box<F>>>,
200}
201
202impl<F: Future> Future for Caught<F> {
203 type Output = Result<F::Output, Bug>;
204
205 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
206 let operation = self.operation;
207 let Some(work) = self.work.as_mut() else {
208 panic!("{operation} polled after it finished");
209 };
210 match location::catch_located(operation, || work.as_mut().poll(cx)) {
211 Ok(Poll::Pending) => Poll::Pending,
212 Ok(Poll::Ready(value)) => {
213 self.work = None;
214 Poll::Ready(Ok(value))
215 }
216 Err((payload, at)) => {
217 let bug = bug_of(operation, payload, at);
218 let work = self.work.take();
219 if let Err(payload) = catch_unwind(AssertUnwindSafe(move || drop(work))) {
220 tracing::error!(
221 operation,
222 "dropping work that panicked panicked again: {}",
223 panic_message(payload.as_ref())
224 );
225 std::mem::forget(payload);
226 }
227 Poll::Ready(Err(bug))
228 }
229 }
230 }
231}
232
233#[cfg(test)]
234#[path = "lib_tests.rs"]
235mod tests;