keramics_core/errors.rs
1/* Copyright 2024-2025 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)]
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 /// Retrieves a string representation of the error.
38 pub fn to_string(&self) -> String {
39 self.messages.join("\n")
40 }
41}
42
43impl Error for ErrorTrace {}
44
45impl fmt::Display for ErrorTrace {
46 /// Formats the error for display.
47 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
48 write!(
49 formatter,
50 "{}",
51 self.messages
52 .iter()
53 .enumerate()
54 .map(|(frame_index, message_string)| format!("#{} {}", frame_index, message_string))
55 .collect::<Vec<String>>()
56 .join("\n")
57 )
58 }
59}