Skip to main content

klauthed_error/code/
error_code.rs

1use std::borrow::Cow;
2use std::fmt;
3
4/// A stable, machine-readable error code for logs and API responses.
5///
6/// Codes follow a `domain.reason` convention (e.g. `config.missing_required`,
7/// `data.unavailable`). They are usually `&'static str` constants, but a dynamic
8/// `String` is supported for codes assembled at runtime.
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11#[cfg_attr(feature = "serde", serde(transparent))]
12pub struct ErrorCode(Cow<'static, str>);
13
14impl ErrorCode {
15    /// A code from a static string — the common case.
16    pub const fn new(code: &'static str) -> Self {
17        ErrorCode(Cow::Borrowed(code))
18    }
19
20    /// A code assembled at runtime.
21    pub fn from_string(code: String) -> Self {
22        ErrorCode(Cow::Owned(code))
23    }
24
25    /// The code as a string slice.
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl fmt::Display for ErrorCode {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37impl From<&'static str> for ErrorCode {
38    fn from(code: &'static str) -> Self {
39        ErrorCode::new(code)
40    }
41}
42
43impl From<String> for ErrorCode {
44    fn from(code: String) -> Self {
45        ErrorCode::from_string(code)
46    }
47}