rusty_handlebars_parser/
error.rs

1//! Error handling for the Handlebars parser
2//!
3//! This module provides error types and handling for the template parsing process.
4//! It includes detailed error messages with context about where parsing errors occurred.
5
6use std::{error::Error, fmt::Display};
7use crate::expression::Expression;
8
9/// Error type for template parsing failures
10///
11/// This error type provides detailed information about parsing errors,
12/// including the location and context of the error.
13#[derive(Debug)]
14pub struct ParseError{
15    pub(crate) message: String
16}
17
18/// Returns the last 32 characters of a string for error context
19pub(crate) fn rcap<'a>(src: &'a str) -> &'a str{
20    static CAP_AT: usize = 32;
21
22    if src.len() > CAP_AT{
23        &src[src.len() - CAP_AT ..]
24    } else {
25        src
26    }
27}
28
29impl ParseError{
30    /// Creates a new parse error with context from an expression
31    pub(crate) fn new(message: &str, expression: &Expression<'_>) -> Self{
32        Self{
33            message: format!("{} near \"{}\"", message, expression.around())
34        }
35    }
36
37    /// Creates an error for unclosed blocks
38    pub(crate) fn unclosed(preffix: &str) -> Self{
39        Self{
40            message: format!("unclosed block near {}", rcap(preffix))
41        }
42    }
43}
44
45impl Display for ParseError{
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.write_str(&self.message)
48    }
49}
50
51impl From<std::io::Error> for ParseError{
52    fn from(err: std::io::Error) -> Self {
53        Self{ message: err.to_string()}
54    }
55}
56
57impl Error for ParseError{}
58
59/// Result type for template parsing operations
60pub type Result<T> = std::result::Result<T, ParseError>;