Skip to main content

ttml_processor/
error.rs

1use std::{
2    result::Result as StdResult,
3    str::Utf8Error,
4    string::FromUtf8Error,
5};
6
7use quick_xml::{
8    Reader,
9    events::attributes::AttrError,
10};
11use thiserror::Error;
12
13use crate::parser::state::ParserContext;
14
15/// 记录解析错误发生时的上下文信息
16#[derive(Debug, Default, Clone)]
17pub struct ErrorContext {
18    /// 错误发生时解析器在文件中的字节偏移量
19    pub byte_offset: u64,
20    /// 当前解析到的歌词行 ID(例如 "L3"),如果尚未解析到则为 None
21    pub line_id: Option<String>,
22    /// 当前的 XML 标签路径栈(例如 `["tt", "body", "div", "p", "span"]`)
23    pub tag_stack: Vec<String>,
24    /// 正在处理的属性名
25    pub current_attribute: Option<String>,
26    /// 引发错误的具体原文字符串
27    pub offending_string: Option<String>,
28}
29
30#[derive(Error, Debug)]
31pub enum ParseErrorKind {
32    #[error("XML attribute error: {0}")]
33    AttrError(#[from] AttrError),
34
35    #[error("Unknown XML entity: {0}")]
36    EntityError(String),
37
38    #[error("Invalid timestamp format: {0}")]
39    InvalidTimestamp(String),
40
41    #[error("Missing required attribute: {0}")]
42    MissingAttribute(String),
43
44    #[error("Unexpected end of file")]
45    UnexpectedEof,
46
47    #[error("XML parsing error: {0}")]
48    XmlError(#[from] quick_xml::Error),
49}
50
51#[derive(Error, Debug)]
52pub enum TTMLProcessorError {
53    #[error("{kind} (at byte offset {0})", .context.byte_offset)]
54    ParseError {
55        kind: ParseErrorKind,
56        context: Box<ErrorContext>,
57    },
58
59    #[error("IO error: {0}")]
60    IoError(#[from] std::io::Error),
61
62    #[error("UTF-8 decoding error: {0}")]
63    Utf8Error(#[from] Utf8Error),
64
65    #[error("UTF-8 from bytes error: {0}")]
66    FromUtf8Error(#[from] FromUtf8Error),
67}
68
69// 手动实现转换以方便从 quick-xml 的 write_inner_content 返回的 io::Error 转换为我们自己的错误枚举
70impl From<TTMLProcessorError> for std::io::Error {
71    fn from(err: TTMLProcessorError) -> Self {
72        Self::other(err)
73    }
74}
75
76pub type Result<T> = StdResult<T, TTMLProcessorError>;
77
78/// 错误上下文扩展,用于将 [`ParseErrorKind`] 转换为包含上下文信息的 [`TTMLProcessorError`]
79pub trait ResultExt<T> {
80    /// 注入基础上下文 (基于当前读取器位置和解析状态)
81    ///
82    /// # Errors
83    ///
84    /// 当前置函数返回 `Err(ParseErrorKind)` 时,返回带有上下文信息的
85    /// [`TTMLProcessorError::ParseError`]
86    fn with_context(
87        self,
88        reader: &Reader<&[u8]>,
89        context: &ParserContext,
90    ) -> StdResult<T, TTMLProcessorError>;
91
92    /// 注入带有特定属性名的上下文
93    ///
94    /// # Errors
95    ///
96    /// 当前置函数返回 `Err(ParseErrorKind)` 时,返回带有属性名与上下文信息的
97    /// [`TTMLProcessorError::ParseError`]
98    fn with_attr_context(
99        self,
100        reader: &Reader<&[u8]>,
101        context: &ParserContext,
102        attr_name: &str,
103    ) -> StdResult<T, TTMLProcessorError>;
104}
105
106impl<T> ResultExt<T> for StdResult<T, ParseErrorKind> {
107    fn with_context(
108        self,
109        reader: &Reader<&[u8]>,
110        context: &ParserContext,
111    ) -> StdResult<T, TTMLProcessorError> {
112        self.map_err(|kind| TTMLProcessorError::ParseError {
113            kind,
114            context: Box::new(ErrorContext {
115                byte_offset: reader.buffer_position(),
116                line_id: context.current_line_id.clone(),
117                tag_stack: context.tag_stack.clone(),
118                current_attribute: None,
119                offending_string: None,
120            }),
121        })
122    }
123
124    fn with_attr_context(
125        self,
126        reader: &Reader<&[u8]>,
127        context: &ParserContext,
128        attr_name: &str,
129    ) -> StdResult<T, TTMLProcessorError> {
130        self.map_err(|kind| TTMLProcessorError::ParseError {
131            kind,
132            context: Box::new(ErrorContext {
133                byte_offset: reader.buffer_position(),
134                line_id: context.current_line_id.clone(),
135                tag_stack: context.tag_stack.clone(),
136                current_attribute: Some(attr_name.to_string()),
137                offending_string: None,
138            }),
139        })
140    }
141}
142
143pub trait OptionExt<T> {
144    /// 将缺失属性错误转换为带上下文的解析错误。
145    ///
146    /// # Errors
147    ///
148    /// 当 `Option` 为 `None` 时,返回 [`TTMLProcessorError::ParseError`],其错误类型为
149    /// [`ParseErrorKind::MissingAttribute`]
150    fn context_missing_attr(
151        self,
152        reader: &Reader<&[u8]>,
153        context: &ParserContext,
154        attr_name: &str,
155    ) -> StdResult<T, TTMLProcessorError>;
156}
157
158impl<T> OptionExt<T> for Option<T> {
159    fn context_missing_attr(
160        self,
161        reader: &Reader<&[u8]>,
162        context: &ParserContext,
163        attr_name: &str,
164    ) -> StdResult<T, TTMLProcessorError> {
165        self.ok_or_else(|| ParseErrorKind::MissingAttribute(attr_name.to_string()))
166            .with_attr_context(reader, context, attr_name)
167    }
168}