Skip to main content

flareapp_core/report/
mod.rs

1//! Error reports: what Flare receives on `/v1/errors`.
2
3mod encode;
4
5use std::any::type_name;
6use std::collections::BTreeMap;
7use std::error::Error;
8use std::fmt;
9use std::io;
10use std::panic::{self, AssertUnwindSafe, Location};
11use std::slice;
12use std::sync::Arc;
13
14use serde_json::Value;
15
16use flareapp_otlp::now_unix_nanos;
17
18pub(crate) use self::encode::fields_to_json;
19use crate::debug::flare_debug;
20use crate::entry_point::{EntryPoint, current_span_entry_point, resolve_entry_point};
21use crate::level::Level;
22use crate::scope::Scope;
23use crate::source_path;
24
25/// The id of one report, a random UUID. Flare calls it the tracking UUID.
26///
27/// Show it to your users ("error id: …"), so they can refer to one specific error.
28#[derive(Clone, Copy, PartialEq, Eq, Hash)]
29pub struct ReportId(u128);
30
31/// The 4 bits of a UUID that hold its version.
32const UUID_VERSION_BITS: u128 = 0xf << 76;
33
34/// Version 4 in the version bits: a UUID made of random bits.
35const UUID_VERSION_4: u128 = 0x4 << 76;
36
37/// The 2 bits of a UUID that hold its variant.
38const UUID_VARIANT_BITS: u128 = 0x3 << 62;
39
40/// The variant `10` in the variant bits: the standard UUID layout of RFC 9562.
41const UUID_VARIANT_STANDARD: u128 = 0x2 << 62;
42
43impl ReportId {
44    /// Creates a random version 4 UUID.
45    fn random() -> Self {
46        let id = fastrand::u128(..);
47        let id = (id & !UUID_VERSION_BITS) | UUID_VERSION_4;
48        let id = (id & !UUID_VARIANT_BITS) | UUID_VARIANT_STANDARD;
49
50        Self(id)
51    }
52}
53
54impl fmt::Display for ReportId {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        let id = self.0;
57
58        write!(
59            f,
60            "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
61            id >> 96,
62            (id >> 80) & 0xffff,
63            (id >> 64) & 0xffff,
64            (id >> 48) & 0xffff,
65            id & 0xffff_ffff_ffff,
66        )
67    }
68}
69
70impl fmt::Debug for ReportId {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(f, "ReportId({self})")
73    }
74}
75
76/// One line of a stack trace.
77#[expect(
78    clippy::struct_field_names,
79    reason = "field names mirror Flare's frame format"
80)]
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Frame {
83    /// The source file, like `/app/src/orders.rs`.
84    pub file: String,
85    /// The line in the source file.
86    pub line_number: u32,
87    /// The column in the source file, when known.
88    pub column_number: Option<u32>,
89    /// The function, like `create`.
90    pub method: Option<String>,
91    /// The module or type the function belongs to, like `my_app::orders::OrderService`.
92    pub class: Option<String>,
93    /// Whether the frame is part of your application, not of a dependency or the
94    /// standard library.
95    pub is_application_frame: bool,
96    /// The address in memory that this frame returns to. Flare uses it to find the
97    /// function, file and line in an uploaded debug file, so an app can ship a
98    /// stripped binary. It is `None` when Flare must keep the frame as it is.
99    pub instruction_addr: Option<usize>,
100}
101
102impl Frame {
103    /// Creates a frame for a code location, like the place where a report was made.
104    pub fn from_location(location: &Location<'_>) -> Self {
105        Self {
106            file: location.file().to_owned(),
107            line_number: location.line(),
108            column_number: Some(location.column()),
109            method: None,
110            class: None,
111            is_application_frame: true,
112            instruction_addr: None,
113        }
114    }
115}
116
117/// A binary or library that was loaded in the app when the report was made.
118///
119/// Flare uses it to link the address of a frame to the debug file of that binary.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct DebugImage {
122    /// The ID that links this binary to its debug file, like
123    /// `f12a7db2-03d7-370d-a820-107402c0c6e7`.
124    pub debug_id: String,
125    /// The address in memory where the binary starts.
126    pub image_addr: usize,
127    /// The size of the binary in memory, in bytes.
128    pub image_size: usize,
129    /// The path of the binary or library, like
130    /// `/usr/lib/system/libsystem_pthread.dylib`.
131    ///
132    /// Flare shows which library a frame is in, and tells system libraries apart
133    /// from the binaries of the app. It is `None` when the operating system gives no
134    /// path. On Linux, the main binary of the app has no path.
135    pub code_file: Option<String>,
136}
137
138/// A stack trace after the worker thread resolved it.
139#[derive(Debug, Default)]
140pub struct StackTrace {
141    /// The frames, innermost first.
142    pub frames: Vec<Frame>,
143    /// The binaries and libraries that hold the addresses of the frames.
144    pub debug_images: Vec<DebugImage>,
145}
146
147/// A captured stack trace that is not resolved yet.
148///
149/// Resolving finds the function, file and line of each address in the stack
150/// trace, and that is slow. So the worker thread resolves the stack trace, and
151/// your code does not wait for it.
152///
153/// The `flareapp-backtrace` crate implements this trait.
154pub trait ResolveFrames: Send + fmt::Debug {
155    /// Resolves the stack trace and returns its frames.
156    ///
157    /// `location` is the place where the report was made. When the stack trace
158    /// does not include `location`, an implementation can add `location` as the
159    /// first frame.
160    fn resolve(self: Box<Self>, location: &Frame) -> StackTrace;
161}
162
163/// One error, panic or message, on its way to Flare.
164#[derive(Debug)]
165pub struct Report {
166    id: ReportId,
167    exception_class: String,
168    message: String,
169    level: Option<Level>,
170    handled: bool,
171    seen_at_unix_nano: u64,
172    /// The place where the report was made. It is the only frame when no stack
173    /// trace is available.
174    location: Frame,
175    /// The captured stack trace. The worker thread resolves it with
176    /// [`Report::resolve_frames`].
177    frames: Option<Box<dyn ResolveFrames>>,
178    context: BTreeMap<String, Value>,
179    attributes: BTreeMap<String, Value>,
180    scope: Scope,
181    /// The entry point the report is filed under, set by
182    /// [`Report::resolve_entry_point`] or by
183    /// [`LogLine::to_report`](crate::LogLine::to_report). Without one, the report
184    /// gets the command line of the process.
185    pub(crate) entry_point: Option<EntryPoint>,
186    application_path: Option<String>,
187}
188
189impl Report {
190    /// Creates a report with an exception class and a message.
191    ///
192    /// `location` is the place where the report was made, like
193    /// `std::panic::Location::caller()`. Without a stack trace, this place is the
194    /// only frame of the report.
195    ///
196    /// # Examples
197    ///
198    /// `Location::caller()` returns the place that called the current function.
199    /// Mark a helper function that creates reports with `#[track_caller]`. Then
200    /// `Location::caller()` returns the place that called the helper, and not a
201    /// place inside the helper:
202    ///
203    /// ```
204    /// use std::panic::Location;
205    ///
206    /// use flareapp_core::Report;
207    ///
208    /// #[track_caller]
209    /// fn payment_failed() -> Report {
210    ///     Report::new("my_app::PaymentFailed", "payment failed", Location::caller())
211    /// }
212    ///
213    /// // The location of this report is this line, not the line in the helper.
214    /// let report = payment_failed();
215    /// ```
216    pub fn new<C, M>(exception_class: C, message: M, location: &Location<'_>) -> Self
217    where
218        C: Into<String>,
219        M: Into<String>,
220    {
221        let location = Frame::from_location(location);
222
223        Self {
224            id: ReportId::random(),
225            exception_class: exception_class.into(),
226            message: message.into(),
227            level: None,
228            handled: true,
229            seen_at_unix_nano: now_unix_nanos(),
230            location,
231            frames: None,
232            context: BTreeMap::new(),
233            attributes: BTreeMap::new(),
234            scope: Scope::default(),
235            entry_point: None,
236            application_path: None,
237        }
238    }
239
240    /// Creates a report for an error. The exception class is the Rust type of the
241    /// error, and the message is its `Display` output.
242    ///
243    /// For a `dyn Error`, the exception class is the class that
244    /// [`erased_exception_class`] returns. When that function finds no class, the
245    /// class is `Error`.
246    pub fn from_error<E: ReportableError + ?Sized>(error: &E, location: &Location<'_>) -> Self {
247        Self::new(exception_class(error), error.to_string(), location)
248    }
249
250    /// Creates a report for an error whose type is hidden, like the error in a
251    /// `Box<dyn Error>`. The message is the `Display` output of the error.
252    ///
253    /// The exception class is the class that [`erased_exception_class`] returns,
254    /// so a `std::io::Error` gets its real type name. When that function finds no
255    /// class, the class is `Error`.
256    pub fn from_erased_error(error: &(dyn Error + 'static), location: &Location<'_>) -> Self {
257        let class =
258            erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned());
259
260        Self::new(class, error.to_string(), location)
261    }
262
263    /// Creates a report for a message, like a log line that needs attention.
264    pub fn from_message<M: Into<String>>(
265        message: M,
266        level: Level,
267        location: &Location<'_>,
268    ) -> Self {
269        let mut report = Self::new("Log", message, location);
270        report.level = Some(level);
271
272        report
273    }
274
275    /// Returns the tracking id of the report.
276    pub fn id(&self) -> ReportId {
277        self.id
278    }
279
280    /// Returns the exception class, like `std::io::error::Error`.
281    pub fn exception_class(&self) -> &str {
282        &self.exception_class
283    }
284
285    /// Changes the exception class, which Flare groups errors by.
286    pub fn set_exception_class<C: Into<String>>(&mut self, exception_class: C) {
287        self.exception_class = exception_class.into();
288    }
289
290    /// Returns the message.
291    pub fn message(&self) -> &str {
292        &self.message
293    }
294
295    /// Returns `true` when your code handled the error, and `false` for a panic.
296    pub fn handled(&self) -> bool {
297        self.handled
298    }
299
300    /// Marks the error as handled by your code (`true`, the default) or not.
301    pub fn set_handled(&mut self, handled: bool) {
302        self.handled = handled;
303    }
304
305    /// Adds a piece of context to this report only.
306    pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
307        self.context.insert(key.into(), value.into());
308    }
309
310    /// Adds an attribute to this report only, like `thread.name`.
311    pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
312        self.attributes.insert(key.into(), value.into());
313    }
314
315    /// Sets the place where the report was made, when it differs from the
316    /// `location` given to [`Report::new`]. Without a stack trace, this place is
317    /// the only frame.
318    pub fn set_location(&mut self, location: Frame) {
319        self.location = location;
320    }
321
322    /// Sets the stack trace. The worker thread resolves it before sending.
323    pub fn set_frames<R: ResolveFrames + 'static>(&mut self, frames: R) {
324        self.frames = Some(Box::new(frames));
325    }
326
327    /// Adds the scope and the application path, just before the report is queued.
328    ///
329    /// Also joins the report location with the workspace root, so the location has
330    /// the same path as the frames from the debug info.
331    pub(crate) fn attach(
332        &mut self,
333        scope: Scope,
334        application_path: Option<String>,
335        workspace_root: Option<&str>,
336    ) {
337        self.scope = scope;
338        self.application_path = application_path;
339
340        if self.location.is_application_frame {
341            self.location.file = source_path::absolute(workspace_root, &self.location.file);
342        }
343    }
344
345    /// Decides which entry point the report is filed under, in the order of the
346    /// [`EntryPoint`] docs. This function keeps the entry point that a log
347    /// line already resolved.
348    ///
349    /// Call this function on the thread that made the report, because the nested
350    /// scopes and the `tracing` spans belong to that thread. The merged scope from
351    /// [`Report::attach`] does not work here. A nested scope comes before the
352    /// spans and the app-wide scope comes after them, but the merged scope mixes
353    /// the two.
354    pub(crate) fn resolve_entry_point(&mut self) {
355        if self.entry_point.is_none() {
356            self.entry_point = Some(resolve_entry_point(current_span_entry_point));
357        }
358    }
359
360    /// Turns the captured stack trace into frames, and returns the report that
361    /// the worker thread can encode. Resolving is slow, so only the worker thread
362    /// calls this function.
363    ///
364    /// A [`ResolveFrames`] implementation can panic. A panic that nothing catches
365    /// ends the worker thread, and the Flare client does not start a new worker
366    /// thread. So this function catches the panic. The report then has the
367    /// report location as its only frame. When `debug` is `true`, this function
368    /// also prints a warning.
369    pub(crate) fn resolve_frames(mut self, debug: bool) -> ResolvedReport {
370        let stack_trace = self
371            .frames
372            .take()
373            .map_or_else(StackTrace::default, |frames| {
374                panic::catch_unwind(AssertUnwindSafe(|| frames.resolve(&self.location)))
375                    .unwrap_or_else(|_| {
376                        flare_debug!(
377                            debug,
378                            WARN,
379                            "resolving the stack trace panicked, so the only frame is the report location"
380                        );
381
382                        StackTrace::default()
383                    })
384            });
385
386        ResolvedReport {
387            report: self,
388            stack_trace,
389        }
390    }
391}
392
393/// A report whose stack trace the worker thread resolved.
394///
395/// Only a resolved report can be encoded, so a report never goes out without its
396/// frames. [`Report::resolve_frames`] creates it.
397#[derive(Debug)]
398pub(crate) struct ResolvedReport {
399    report: Report,
400    stack_trace: StackTrace,
401}
402
403impl ResolvedReport {
404    /// Returns the frames. Without a stack trace, the place where the report was
405    /// made is the only frame.
406    fn frames(&self) -> &[Frame] {
407        if self.stack_trace.frames.is_empty() {
408            slice::from_ref(&self.report.location)
409        } else {
410            &self.stack_trace.frames
411        }
412    }
413
414    /// Returns the binaries and libraries that hold the addresses of the frames.
415    fn debug_images(&self) -> &[DebugImage] {
416        &self.stack_trace.debug_images
417    }
418}
419
420/// The exception class of an error without a name. Flare needs a non-empty one.
421pub(crate) const FALLBACK_EXCEPTION_CLASS: &str = "Error";
422
423/// An error that the Flare client can report: an error type that does not borrow
424/// data, or a `dyn Error`.
425///
426/// [`Report::from_error`] and `flareapp::report_error` take this trait instead of
427/// [`Error`]. For a `dyn Error`, the Flare client looks up the real type of the
428/// error, like `std::io::Error`. Rust can only do that for an error that is
429/// `'static`.
430///
431/// Every `'static` type that implements [`Error`] implements this trait.
432/// `dyn Error`, `dyn Error + Send` and `dyn Error + Send + Sync` also implement
433/// this trait. Other crates cannot implement this trait.
434///
435/// In a function argument, write `&(dyn Error + 'static)` instead of
436/// `&dyn Error`. In that place, Rust reads `&dyn Error` as an error that can
437/// borrow data, and such an error does not implement this trait.
438pub trait ReportableError: Error + sealed::Sealed {
439    /// Returns the error as a `dyn Error`, so the Flare client can look up the
440    /// real type of the error.
441    fn as_dyn_error(&self) -> &(dyn Error + 'static);
442}
443
444impl<E: Error + 'static> ReportableError for E {
445    fn as_dyn_error(&self) -> &(dyn Error + 'static) {
446        self
447    }
448}
449
450impl ReportableError for dyn Error + 'static {
451    fn as_dyn_error(&self) -> &(dyn Error + 'static) {
452        self
453    }
454}
455
456impl ReportableError for dyn Error + Send + 'static {
457    fn as_dyn_error(&self) -> &(dyn Error + 'static) {
458        self
459    }
460}
461
462impl ReportableError for dyn Error + Send + Sync + 'static {
463    fn as_dyn_error(&self) -> &(dyn Error + 'static) {
464        self
465    }
466}
467
468mod sealed {
469    use std::error::Error;
470
471    /// Stops other crates from implementing
472    /// [`ReportableError`](super::ReportableError).
473    pub trait Sealed {}
474
475    impl<E: Error + 'static> Sealed for E {}
476    impl Sealed for dyn Error + 'static {}
477    impl Sealed for dyn Error + Send + 'static {}
478    impl Sealed for dyn Error + Send + Sync + 'static {}
479}
480
481/// Returns the exception class for an error: its Rust type name.
482///
483/// A `Box`, an `Arc` or a `&'static` reference around an error has the same
484/// class as the error. So `report_error(&error)` and
485/// `report_error(&Arc::new(error))` give the same class. [`inner_type_name`]
486/// removes these types from the type name.
487///
488/// A `dyn Error` has no type name at runtime, like the error in an
489/// `Arc<dyn Error + Send + Sync>`. In that case, this function uses the class that
490/// [`erased_exception_class`] returns.
491fn exception_class<E: ReportableError + ?Sized>(error: &E) -> String {
492    let type_name = inner_type_name(type_name::<E>());
493    if !type_name.starts_with("dyn ") {
494        return type_name.to_owned();
495    }
496
497    erased_exception_class(error.as_dyn_error())
498        .unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
499}
500
501/// Removes every `&`, `Box` and `Arc` around a type name. For example,
502/// `&alloc::sync::Arc<my_app::OrderFailed>` becomes `my_app::OrderFailed`.
503///
504/// The standard library implements [`Error`] for `&T`, `Box<T>` and `Arc<T>`, and
505/// passes each call to `T`. Other types around an error, like `Rc<T>` and
506/// `&mut T`, do not implement [`Error`].
507fn inner_type_name(mut name: &str) -> &str {
508    // The output of `type_name` can change between Rust versions, so the prefixes
509    // come from `type_name` too, like `alloc::sync::Arc<`.
510    let wrappers =
511        [type_name::<Box<()>>(), type_name::<Arc<()>>()].map(|wrapper| wrapper.strip_suffix("()>"));
512    while let Some(inner) = name.strip_prefix('&').or_else(|| {
513        wrappers
514            .iter()
515            .flatten()
516            .find_map(|prefix| name.strip_prefix(prefix)?.strip_suffix('>'))
517    }) {
518        name = inner;
519    }
520
521    name
522}
523
524/// Returns the exception class for an error whose type is hidden, like the error
525/// in a `Box<dyn Error>` or the root cause of an `anyhow::Error`.
526///
527/// Rust has no type name for these at runtime. `std::io::Error` is common enough to
528/// recognize, also inside an `Arc<dyn Error>`. Other errors get the name at the
529/// start of their `Debug` output: the struct or enum variant name for derived
530/// `Debug`, or a path like `reqwest::Error` that some crates print. Returns `None`
531/// when that output does not start with a name, like a quoted message.
532pub fn erased_exception_class(error: &(dyn Error + 'static)) -> Option<String> {
533    let error = without_arcs(error);
534    if error.is::<io::Error>() {
535        return Some(type_name::<io::Error>().to_owned());
536    }
537
538    debug_name(&format!("{error:?}")).map(str::to_owned)
539}
540
541/// Returns the error inside every `Arc<dyn Error>` around an error.
542///
543/// The type of an `Arc<dyn Error>` is the `Arc`, so a `std::io::Error` in the
544/// `Arc` is only found after this function removes the `Arc`.
545fn without_arcs<'a>(mut error: &'a (dyn Error + 'static)) -> &'a (dyn Error + 'static) {
546    loop {
547        error = if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send + Sync>>() {
548            arc.as_ref()
549        } else if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send>>() {
550            arc.as_ref()
551        } else if let Some(arc) = error.downcast_ref::<Arc<dyn Error>>() {
552            arc.as_ref()
553        } else {
554            return error;
555        };
556    }
557}
558
559/// Returns the name at the start of a `Debug` output, when it has one: a word like
560/// `RowNotFound`, or a path like `reqwest::Error`, which some crates print in their
561/// own `Debug` output.
562fn debug_name(debug: &str) -> Option<&str> {
563    let is_name_character = |character: char| character.is_alphanumeric() || character == '_';
564    if !debug.starts_with(is_name_character) {
565        return None;
566    }
567
568    // Skip the first name, then each `::name` after it.
569    let mut rest = debug.trim_start_matches(is_name_character);
570    while let Some(after) = rest.strip_prefix("::")
571        && after.starts_with(is_name_character)
572    {
573        rest = after.trim_start_matches(is_name_character);
574    }
575
576    debug.get(..debug.len() - rest.len())
577}
578
579#[cfg(test)]
580mod tests {
581    use std::io;
582    use std::path::Path;
583
584    use super::*;
585
586    #[derive(Debug)]
587    struct OrderFailed {
588        order_id: u32,
589    }
590
591    impl fmt::Display for OrderFailed {
592        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593            write!(f, "order {} failed", self.order_id)
594        }
595    }
596
597    impl Error for OrderFailed {}
598
599    #[test]
600    fn report_ids_are_uuid_v4() {
601        let id = ReportId::random().to_string();
602
603        assert_eq!(id.len(), 36);
604        assert_eq!(id.chars().nth(14), Some('4'));
605        assert!(matches!(id.chars().nth(19), Some('8' | '9' | 'a' | 'b')));
606    }
607
608    #[test]
609    fn uses_the_type_name_as_exception_class() {
610        assert_eq!(
611            exception_class(&OrderFailed { order_id: 7 }),
612            "flareapp_core::report::tests::OrderFailed"
613        );
614    }
615
616    #[test]
617    fn a_static_reference_to_an_error_has_the_class_of_the_error() {
618        static ERROR: OrderFailed = OrderFailed { order_id: 7 };
619        static REFERENCE: &OrderFailed = &ERROR;
620
621        assert_eq!(exception_class(&REFERENCE), exception_class(&ERROR));
622        assert_eq!(exception_class(&&REFERENCE), exception_class(&ERROR));
623    }
624
625    #[test]
626    fn an_error_in_a_box_or_an_arc_has_the_class_of_the_error() {
627        let expected = exception_class(&OrderFailed { order_id: 7 });
628
629        let boxed = Box::new(OrderFailed { order_id: 7 });
630        let shared = Arc::new(OrderFailed { order_id: 7 });
631        let both = Arc::new(Box::new(OrderFailed { order_id: 7 }));
632        assert_eq!(exception_class(&boxed), expected);
633        assert_eq!(exception_class(&shared), expected);
634        assert_eq!(exception_class(&both), expected);
635    }
636
637    #[test]
638    fn an_arc_of_a_dyn_error_has_the_debug_name() {
639        let error: Arc<dyn Error + Send + Sync> = Arc::new(OrderFailed { order_id: 7 });
640
641        assert_eq!(exception_class(&error), "OrderFailed");
642    }
643
644    #[test]
645    fn a_reference_to_a_dyn_error_has_the_debug_name() {
646        let error: &dyn Error = &OrderFailed { order_id: 7 };
647
648        assert_eq!(exception_class(&error), "OrderFailed");
649    }
650
651    #[test]
652    fn from_error_uses_the_exception_class_of_the_error() {
653        let error = OrderFailed { order_id: 7 };
654        let shared = Arc::new(OrderFailed { order_id: 7 });
655        let as_dyn: &(dyn Error + 'static) = &error;
656
657        let by_value = Report::from_error(&error, Location::caller());
658        let by_arc = Report::from_error(&shared, Location::caller());
659        let by_dyn = Report::from_error(as_dyn, Location::caller());
660
661        assert_eq!(by_arc.exception_class(), by_value.exception_class());
662        assert_eq!(by_dyn.exception_class(), "OrderFailed");
663    }
664
665    #[test]
666    fn io_errors_are_named_after_their_std_type() {
667        let error = io::Error::other("disk full");
668
669        // The path depends on the Rust version: older versions say `std::…`, newer
670        // ones `core::…`.
671        assert!(exception_class(&error).ends_with("io::error::Error"));
672    }
673
674    #[test]
675    fn uses_the_debug_name_for_dyn_errors() {
676        let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
677
678        assert_eq!(exception_class(&*error), "OrderFailed");
679    }
680
681    #[test]
682    fn a_dyn_io_error_keeps_its_type_name() {
683        let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
684
685        let class = exception_class(error.as_ref());
686
687        assert!(class.ends_with("io::error::Error"), "{class}");
688    }
689
690    #[test]
691    fn an_io_error_in_an_arc_of_a_dyn_error_keeps_its_type_name() {
692        let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
693
694        let class = exception_class(&error);
695
696        assert!(class.ends_with("io::error::Error"), "{class}");
697    }
698
699    #[test]
700    fn reports_of_dyn_io_errors_keep_their_type_name() {
701        let error: Box<dyn Error + Send + Sync> = Box::new(io::Error::other("disk full"));
702
703        let report = Report::from_error(error.as_ref(), Location::caller());
704
705        let class = report.exception_class();
706        assert!(class.ends_with("io::error::Error"), "{class}");
707    }
708
709    #[test]
710    fn hidden_io_errors_in_an_arc_keep_their_type_name() {
711        let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
712
713        let class = erased_exception_class(&error).unwrap();
714
715        assert!(class.ends_with("io::error::Error"), "{class}");
716    }
717
718    #[test]
719    fn hidden_io_errors_keep_their_type_name() {
720        let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
721
722        let class = erased_exception_class(error.as_ref()).unwrap();
723
724        assert!(class.ends_with("io::error::Error"));
725    }
726
727    #[test]
728    fn other_hidden_errors_get_their_debug_name() {
729        let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
730
731        let class = erased_exception_class(error.as_ref());
732
733        assert_eq!(class.as_deref(), Some("OrderFailed"));
734    }
735
736    /// Like `reqwest::Error`, whose `Debug` output starts with its path.
737    #[test]
738    fn hidden_errors_keep_the_path_their_debug_output_starts_with() {
739        struct RequestFailed;
740
741        impl fmt::Debug for RequestFailed {
742            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743                f.debug_struct("reqwest::Error")
744                    .field("kind", &"Request")
745                    .finish()
746            }
747        }
748
749        impl fmt::Display for RequestFailed {
750            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751                f.write_str("error sending request")
752            }
753        }
754
755        impl Error for RequestFailed {}
756
757        assert_eq!(
758            erased_exception_class(&RequestFailed).as_deref(),
759            Some("reqwest::Error")
760        );
761    }
762
763    #[test]
764    fn debug_names_end_where_the_name_ends() {
765        assert_eq!(
766            debug_name("Database(SqliteError { code: 1 })"),
767            Some("Database")
768        );
769        assert_eq!(debug_name("Error: boom"), Some("Error"));
770        assert_eq!(debug_name("my_app::Error::"), Some("my_app::Error"));
771    }
772
773    #[test]
774    fn debug_output_that_starts_without_a_name_has_no_debug_name() {
775        assert_eq!(debug_name("\"plain message\""), None);
776        assert_eq!(debug_name("::Error"), None);
777        assert_eq!(debug_name(""), None);
778    }
779
780    #[test]
781    fn hidden_errors_without_a_debug_name_have_no_class() {
782        let error: Box<dyn Error> = "plain message".into();
783
784        assert_eq!(erased_exception_class(error.as_ref()), None);
785    }
786
787    #[test]
788    fn reports_of_hidden_io_errors_keep_their_type_name() {
789        let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
790
791        let report = Report::from_erased_error(error.as_ref(), Location::caller());
792
793        let class = report.exception_class();
794        assert!(class.ends_with("io::error::Error"), "{class}");
795    }
796
797    #[test]
798    fn reports_of_hidden_errors_without_a_debug_name_are_named_error() {
799        let error: Box<dyn Error> = "plain message".into();
800
801        let report = Report::from_erased_error(error.as_ref(), Location::caller());
802
803        assert_eq!(report.exception_class(), "Error");
804    }
805
806    #[test]
807    fn reports_of_hidden_errors_have_the_display_output_as_message() {
808        let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
809
810        let report = Report::from_erased_error(error.as_ref(), Location::caller());
811
812        assert_eq!(report.message(), "order 7 failed");
813    }
814
815    #[test]
816    fn messages_are_logs() {
817        let report = Report::from_message("Stock low", Level::Warning, Location::caller());
818
819        assert_eq!(report.exception_class(), "Log");
820        assert_eq!(report.level, Some(Level::Warning));
821    }
822
823    #[test]
824    fn falls_back_to_the_report_location_without_frames() {
825        #[derive(Debug)]
826        struct NoFrames;
827
828        impl ResolveFrames for NoFrames {
829            fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
830                StackTrace::default()
831            }
832        }
833
834        let mut report = Report::new("Panic", "boom", Location::caller());
835        report.set_frames(NoFrames);
836        let resolved = report.resolve_frames(false);
837
838        assert_eq!(resolved.frames().len(), 1);
839        assert!(resolved.frames()[0].file.ends_with("mod.rs"));
840    }
841
842    #[test]
843    fn a_panic_while_resolving_frames_does_not_stop_the_worker_thread() {
844        #[derive(Debug)]
845        struct PanicsOnResolve;
846
847        impl ResolveFrames for PanicsOnResolve {
848            fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
849                panic!("cannot read the debug info");
850            }
851        }
852
853        let transport = crate::test_support::run(
854            |config| config,
855            || {
856                let client = crate::current().unwrap();
857                let mut first = Report::new("First", "one", Location::caller());
858                first.set_frames(PanicsOnResolve);
859                client.send_report(first);
860                client.send_report(Report::new("Second", "two", Location::caller()));
861            },
862        );
863
864        let reports: Vec<Value> = transport
865            .requests()
866            .iter()
867            .filter(|request| request.signal == crate::transport::Signal::Errors)
868            .map(crate::test_support::json)
869            .collect();
870        let classes: Vec<&Value> = reports
871            .iter()
872            .map(|report| &report["exceptionClass"])
873            .collect();
874        assert_eq!(classes, ["First", "Second"]);
875        assert_eq!(reports[0]["stacktrace"].as_array().map(Vec::len), Some(1));
876    }
877
878    #[test]
879    fn a_report_without_a_stack_trace_has_no_debug_images() {
880        let report = Report::new("Panic", "boom", Location::caller());
881
882        assert_eq!(report.resolve_frames(false).debug_images(), []);
883    }
884
885    fn located_at(file: &str, is_application_frame: bool) -> Report {
886        let mut report = Report::new("Panic", "boom", Location::caller());
887        report.set_location(Frame {
888            file: file.to_owned(),
889            line_number: 12,
890            column_number: None,
891            method: None,
892            class: None,
893            is_application_frame,
894            instruction_addr: None,
895        });
896
897        report
898    }
899
900    #[test]
901    fn the_report_location_gets_the_workspace_root() {
902        let mut report = located_at("crates/app/src/main.rs", true);
903
904        report.attach(Scope::default(), None, Some("/code/shop"));
905        let resolved = report.resolve_frames(false);
906
907        // `Path` compares components, so the `\` that Windows joins with matches `/`.
908        assert_eq!(
909            Path::new(&resolved.frames()[0].file),
910            Path::new("/code/shop/crates/app/src/main.rs")
911        );
912    }
913
914    #[test]
915    fn an_unknown_location_keeps_its_path() {
916        let mut report = located_at("<unknown>", false);
917
918        report.attach(Scope::default(), None, Some("/code/shop"));
919
920        assert_eq!(report.resolve_frames(false).frames()[0].file, "<unknown>");
921    }
922
923    #[test]
924    fn an_absolute_location_keeps_its_path() {
925        let mut report = located_at("/cargo/registry/src/axum-0.8.9/src/lib.rs", true);
926
927        report.attach(Scope::default(), None, Some("/code/shop"));
928
929        assert_eq!(
930            report.resolve_frames(false).frames()[0].file,
931            "/cargo/registry/src/axum-0.8.9/src/lib.rs"
932        );
933    }
934}