Skip to main content

rich/
errors.rs

1//! Error types.
2//!
3//! Port of the exceptions in upstream `rich/errors.py`. As more of the library
4//! is ported, additional variants are added here rather than scattering ad-hoc
5//! error types across modules.
6
7use std::fmt;
8
9/// Errors produced while parsing colors, styles, or markup.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum RichError {
12    /// A color could not be parsed (`rich.errors.ColorParseError`).
13    ColorParse(String),
14    /// A style definition could not be parsed (`rich.errors.StyleSyntaxError`).
15    StyleSyntax(String),
16    /// Console markup was malformed (`rich.errors.MarkupError`).
17    Markup(String),
18    /// A JSON string could not be parsed (used by `rich.json.JSON`).
19    Json(String),
20    /// A regular expression could not be compiled or run. Python has no rich
21    /// equivalent — it lets `re.error` propagate — but a caller-supplied pattern
22    /// has to fail somewhere, and returning it beats panicking.
23    Regex(String),
24    /// The console's base theme cannot be popped (`rich.theme.ThemeStackError`).
25    ThemeStack(String),
26    /// A theme config file could not be read or parsed. Upstream surfaces
27    /// Python's `configparser` errors (`NoSectionError`, `DuplicateOptionError`,
28    /// `ParsingError`, `InterpolationSyntaxError`) and `OSError` here.
29    ThemeConfig(String),
30}
31
32impl fmt::Display for RichError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            RichError::ColorParse(msg) => write!(f, "color parse error: {msg}"),
36            RichError::StyleSyntax(msg) => write!(f, "style syntax error: {msg}"),
37            RichError::Markup(msg) => write!(f, "markup error: {msg}"),
38            RichError::Json(msg) => write!(f, "json parse error: {msg}"),
39            RichError::Regex(msg) => write!(f, "regex error: {msg}"),
40            RichError::ThemeStack(msg) => write!(f, "theme stack error: {msg}"),
41            RichError::ThemeConfig(msg) => write!(f, "theme config error: {msg}"),
42        }
43    }
44}
45
46impl std::error::Error for RichError {}
47
48/// Convenience alias mirroring the subset of `rich` that raises on bad input.
49pub type Result<T> = std::result::Result<T, RichError>;