Skip to main content

utopia_span/
failure.rs

1//! Errors recorded on spans.
2
3use std::panic::Location;
4
5/// One call in a [`Failure`]'s stack trace, innermost first.
6///
7/// PHP: an entry of `$throwable->getTrace()`.
8#[derive(Debug, Clone, PartialEq, Eq, Default)]
9pub struct Frame {
10    /// The file of the call site, when known.
11    pub file: Option<String>,
12    /// The line of the call site, when known.
13    pub line: Option<u32>,
14    /// The function called.
15    pub function: String,
16    /// The class of the method called, for a method call.
17    pub class: Option<String>,
18    /// How the method was called: `->` or `::`.
19    pub call: Option<String>,
20}
21
22/// An error recorded on a span: what exporters report about it.
23///
24/// It carries what exporters print: the error's type (`class`), message,
25/// code, where it was raised, its stack trace and the error that caused it.
26/// [`Failure::new`] records the caller's location; [`Failure::from_error`]
27/// converts any [`std::error::Error`] with its chain of sources.
28///
29/// PHP: the `\Throwable` passed to `setError()` or `finish()`; `class` is
30/// `$e::class`, `previous` is `getPrevious()`.
31///
32/// ```
33/// use utopia_span::Failure;
34///
35/// let root = Failure::new("LogicException", "root cause");
36/// let error = Failure::new("RuntimeException", "outer").code(42).previous(root);
37///
38/// assert_eq!(error.class(), "RuntimeException");
39/// assert_eq!(error.code_value(), 42);
40/// assert_eq!(error.cause().map(|c| c.message()), Some("root cause"));
41/// ```
42///
43/// ```php
44/// $root = new \LogicException('root cause');
45/// $error = new \RuntimeException('outer', 42, $root);
46///
47/// echo $error::class, "\n";                    // RuntimeException
48/// echo $error->getCode(), "\n";                // 42
49/// echo $error->getPrevious()->getMessage(), "\n"; // root cause
50/// ```
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Failure {
53    class: String,
54    message: Vec<u8>,
55    code: i64,
56    file: String,
57    line: u32,
58    trace: Vec<Frame>,
59    previous: Option<Box<Failure>>,
60}
61
62impl Failure {
63    /// A failure of type `class` with `message`, raised where this is called,
64    /// with code 0, no trace and no cause.
65    ///
66    /// PHP: `new $class($message)`.
67    #[track_caller]
68    pub fn new(class: impl Into<String>, message: impl Into<Vec<u8>>) -> Self {
69        let at = Location::caller();
70        Self {
71            class: class.into(),
72            message: message.into(),
73            code: 0,
74            file: at.file().to_owned(),
75            line: at.line(),
76            trace: Vec::new(),
77            previous: None,
78        }
79    }
80
81    /// A failure describing `error`: its type name, message and chain of
82    /// sources (each source becomes the [`Failure::cause`] of the one before,
83    /// with the type `std::error::Error`).
84    ///
85    /// ```
86    /// use utopia_span::Failure;
87    ///
88    /// let error = "x".parse::<i32>().unwrap_err();
89    /// let failure = Failure::from_error(&error);
90    /// assert_eq!(failure.class(), "core::num::error::ParseIntError");
91    /// assert_eq!(failure.message(), "invalid digit found in string");
92    /// ```
93    #[track_caller]
94    pub fn from_error<E: std::error::Error + ?Sized>(error: &E) -> Self {
95        let mut failure = Failure::new(std::any::type_name::<E>(), error.to_string());
96        let mut sources = Vec::new();
97        let mut source = error.source();
98        while let Some(s) = source {
99            sources.push(Failure::new("std::error::Error", s.to_string()));
100            source = s.source();
101        }
102        let mut cause = None;
103        for mut s in sources.into_iter().rev() {
104            s.previous = cause.map(Box::new);
105            cause = Some(s);
106        }
107        failure.previous = cause.map(Box::new);
108        failure
109    }
110
111    /// Sets the error code.
112    pub fn code(mut self, code: i64) -> Self {
113        self.code = code;
114        self
115    }
116
117    /// Sets where the error was raised.
118    pub fn at(mut self, file: impl Into<String>, line: u32) -> Self {
119        self.file = file.into();
120        self.line = line;
121        self
122    }
123
124    /// Sets the stack trace, innermost call first.
125    pub fn trace(mut self, trace: Vec<Frame>) -> Self {
126        self.trace = trace;
127        self
128    }
129
130    /// Sets the error that caused this one.
131    pub fn previous(mut self, previous: Failure) -> Self {
132        self.previous = Some(Box::new(previous));
133        self
134    }
135
136    /// The error's type.
137    ///
138    /// PHP: `$e::class`.
139    pub fn class(&self) -> &str {
140        &self.class
141    }
142
143    /// The message, when it is UTF-8 (the empty string otherwise; see
144    /// [`Failure::message_bytes`]).
145    ///
146    /// PHP: `getMessage()`.
147    pub fn message(&self) -> &str {
148        std::str::from_utf8(&self.message).unwrap_or_default()
149    }
150
151    /// The message, as bytes.
152    pub fn message_bytes(&self) -> &[u8] {
153        &self.message
154    }
155
156    /// The error code.
157    ///
158    /// PHP: `getCode()`.
159    pub fn code_value(&self) -> i64 {
160        self.code
161    }
162
163    /// The file the error was raised in.
164    ///
165    /// PHP: `getFile()`.
166    pub fn file(&self) -> &str {
167        &self.file
168    }
169
170    /// The line the error was raised at.
171    ///
172    /// PHP: `getLine()`.
173    pub fn line(&self) -> u32 {
174        self.line
175    }
176
177    /// The stack trace, innermost call first.
178    ///
179    /// PHP: `getTrace()`.
180    pub fn frames(&self) -> &[Frame] {
181        &self.trace
182    }
183
184    /// The error that caused this one.
185    ///
186    /// PHP: `getPrevious()`.
187    pub fn cause(&self) -> Option<&Failure> {
188        self.previous.as_deref()
189    }
190}
191
192impl std::fmt::Display for Failure {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        write!(f, "{}: {}", self.class, String::from_utf8_lossy(&self.message))
195    }
196}
197
198impl std::error::Error for Failure {
199    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
200        self.previous.as_deref().map(|p| p as &(dyn std::error::Error + 'static))
201    }
202}