Skip to main content

optic_core/
error.rs

1use std::fmt;
2
3/// Broad category of an error.
4#[derive(Debug, Clone, PartialEq)]
5pub enum OpticErrorKind {
6    Init,
7    OpenGL,
8    Shader,
9    Asset,
10    File,
11    Framebuffer,
12    Custom,
13}
14
15/// The primary error type for the Optic engine.
16///
17/// All fallible functions in the engine return [`OpticResult<T>`].
18/// Errors propagate upward via `?` and can be handled generically
19/// by inspecting [`kind`](OpticError::kind).
20///
21/// ```
22/// use optic_core::*;
23///
24/// fn load_shader(path: &str) -> OpticResult<()> {
25///     Err(OpticError::new(OpticErrorKind::Shader, "compile failed"))
26/// }
27/// ```
28#[derive(Debug, Clone)]
29pub struct OpticError {
30    pub kind: OpticErrorKind,
31    pub msg: String,
32}
33
34impl fmt::Display for OpticError {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "optic error: {}", self.msg)
37    }
38}
39
40impl OpticError {
41    /// Construct an error with a specific kind and message.
42    pub fn new(kind: OpticErrorKind, msg: &str) -> Self {
43        Self {
44            kind,
45            msg: msg.to_string(),
46        }
47    }
48    /// Construct a [`Custom`](OpticErrorKind::Custom) error.
49    pub fn custom(msg: &str) -> Self {
50        Self {
51            kind: OpticErrorKind::Custom,
52            msg: msg.to_string(),
53        }
54    }
55}
56
57/// Convenience alias for `Result<T, OpticError>`.
58pub type OpticResult<T> = Result<T, OpticError>;