Skip to main content

deq_shapes/
error.rs

1//! The only error type the library returns.
2
3use std::fmt;
4
5/// Stable error codes, the same in every port.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ErrorCode {
8    /// No shape has this id.
9    UnknownShape,
10    /// Render, export or flag options are invalid.
11    InvalidOptions,
12    /// A shape parameter value is invalid.
13    InvalidParameter,
14    /// A shape description is invalid.
15    InvalidShape,
16    /// A shape expands to too much geometry.
17    LimitExceeded,
18}
19
20impl ErrorCode {
21    /// The code as the TypeScript reference spells it.
22    #[must_use]
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::UnknownShape => "UNKNOWN_SHAPE",
26            Self::InvalidOptions => "INVALID_OPTIONS",
27            Self::InvalidParameter => "INVALID_PARAMETER",
28            Self::InvalidShape => "INVALID_SHAPE",
29            Self::LimitExceeded => "LIMIT_EXCEEDED",
30        }
31    }
32}
33
34/// Why an operation failed. `code` is stable; the message is for people.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct DeqError {
37    /// The stable error code.
38    pub code: ErrorCode,
39    /// A message for people.
40    pub message: String,
41    /// Validation problems, one line each (for `InvalidOptions`).
42    pub issues: Vec<String>,
43}
44
45impl DeqError {
46    /// An error without separate issues.
47    #[must_use]
48    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
49        Self {
50            code,
51            message: message.into(),
52            issues: Vec::new(),
53        }
54    }
55
56    /// An `InvalidOptions` error: `"<prefix>: <issues joined by '; '>"`.
57    #[must_use]
58    pub fn options(prefix: &str, issues: Vec<String>) -> Self {
59        Self {
60            code: ErrorCode::InvalidOptions,
61            message: format!("{prefix}: {}", issues.join("; ")),
62            issues,
63        }
64    }
65}
66
67impl fmt::Display for DeqError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.write_str(&self.message)
70    }
71}
72
73impl std::error::Error for DeqError {}
74
75/// The result type of the library.
76pub type Result<T> = std::result::Result<T, DeqError>;