keramics_core/errors.rs
1/* Copyright 2024-2026 Joachim Metz <joachim.metz@gmail.com>
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may
5 * obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software
8 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 * License for the specific language governing permissions and limitations
11 * under the License.
12 */
13
14use std::error::Error;
15use std::fmt;
16
17/// Error with traceback information.
18#[derive(Debug, PartialEq)]
19pub struct ErrorTrace {
20 /// The error messages.
21 messages: Vec<String>,
22}
23
24impl ErrorTrace {
25 /// Creates a new error.
26 pub fn new(message_string: String) -> Self {
27 Self {
28 messages: vec![message_string],
29 }
30 }
31
32 /// Adds an additional message to the trace.
33 pub fn add_frame(&mut self, message_string: String) {
34 self.messages.push(message_string);
35 }
36}
37
38impl Error for ErrorTrace {}
39
40impl fmt::Display for ErrorTrace {
41 /// Formats the error for display.
42 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
43 write!(
44 formatter,
45 "{}",
46 self.messages
47 .iter()
48 .enumerate()
49 .map(|(frame_index, message_string)| format!("#{} {}", frame_index, message_string))
50 .collect::<Vec<String>>()
51 .join("\n")
52 )
53 }
54}