cmark_writer/
error.rs

1//! Error handling for CommonMark writer.
2//!
3//! This module provides error types and implementations for handling errors
4//! that can occur during CommonMark writing.
5
6use std::error::Error;
7use std::fmt::{self, Display};
8
9/// Errors that can occur during CommonMark writing.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum WriteError {
12    /// An invalid heading level was encountered (must be 1-6).
13    InvalidHeadingLevel(u8),
14    /// A newline character was found in an inline element where it's not allowed (e.g., in strict mode or specific contexts like table cells, link text, image alt text).
15    NewlineInInlineElement(String),
16    /// An underlying formatting error occurred.
17    FmtError(String),
18    /// An unsupported node type was encountered.
19    UnsupportedNodeType,
20}
21
22impl Display for WriteError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            WriteError::InvalidHeadingLevel(level) => write!(
26                f,
27                "Invalid heading level: {}. Level must be between 1 and 6.",
28                level
29            ),
30            WriteError::NewlineInInlineElement(context) => write!(
31                f,
32                "Newline character found within an inline element ({}) which is not allowed in strict mode or this context.",
33                context
34            ),
35            WriteError::FmtError(msg) => write!(f, "Formatting error: {}", msg),
36            WriteError::UnsupportedNodeType => {
37                write!(f, "Unsupported node type encountered during writing.")
38            }
39        }
40    }
41}
42
43impl Error for WriteError {}
44
45// Allow converting fmt::Error into WriteError for convenience when using `?`
46impl From<fmt::Error> for WriteError {
47    fn from(err: fmt::Error) -> Self {
48        WriteError::FmtError(err.to_string())
49    }
50}
51
52/// Result type alias for writer operations.
53pub type WriteResult<T> = Result<T, WriteError>;