fracturedjson/
error.rs

1use std::fmt::{self, Display};
2
3use crate::model::InputPosition;
4
5/// Error type returned by formatting operations.
6///
7/// This error is returned when JSON parsing fails (invalid syntax, unexpected tokens)
8/// or when formatting constraints are violated (recursion limit exceeded, etc.).
9///
10/// When the error is associated with a specific location in the input, the
11/// `input_position` field will contain the position information, and the
12/// message will include human-readable location details.
13///
14/// # Example
15///
16/// ```rust
17/// use fracturedjson::Formatter;
18///
19/// let mut formatter = Formatter::new();
20/// let result = formatter.reformat("{ invalid json }", 0);
21///
22/// match result {
23///     Ok(_) => println!("Success"),
24///     Err(e) => {
25///         println!("Error: {}", e);
26///         if let Some(pos) = e.input_position {
27///             println!("At row {}, column {}", pos.row, pos.column);
28///         }
29///     }
30/// }
31/// ```
32#[derive(Debug, Clone)]
33pub struct FracturedJsonError {
34    /// The error message, including position information if available.
35    pub message: String,
36
37    /// The position in the input where the error occurred, if applicable.
38    pub input_position: Option<InputPosition>,
39}
40
41impl FracturedJsonError {
42    /// Creates a new error with an optional input position.
43    ///
44    /// If a position is provided, it will be appended to the message
45    /// in a human-readable format.
46    pub fn new(message: impl Into<String>, pos: Option<InputPosition>) -> Self {
47        let message = message.into();
48        let message = if let Some(p) = pos {
49            format!(
50                "{} at idx={}, row={}, col={}",
51                message, p.index, p.row, p.column
52            )
53        } else {
54            message
55        };
56        Self {
57            message,
58            input_position: pos,
59        }
60    }
61
62    /// Creates a new error without position information.
63    pub fn simple(message: impl Into<String>) -> Self {
64        Self::new(message, None)
65    }
66}
67
68impl Display for FracturedJsonError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str(&self.message)
71    }
72}
73
74impl std::error::Error for FracturedJsonError {}