Skip to main content

git_hunk/
error.rs

1use serde::Serialize;
2use std::fmt::{Display, Formatter};
3
4#[derive(Debug, Clone, Serialize)]
5pub struct AppError {
6    pub code: &'static str,
7    pub message: String,
8}
9
10impl AppError {
11    pub fn new(code: &'static str, message: String) -> Self {
12        Self { code, message }
13    }
14
15    pub fn io(err: std::io::Error) -> Self {
16        Self::new("io_error", err.to_string())
17    }
18
19    pub fn to_json_string(&self) -> String {
20        serde_json::to_string_pretty(&ErrorEnvelope {
21            error: self.clone(),
22        })
23        .expect("error should serialize")
24    }
25}
26
27impl Display for AppError {
28    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
29        write!(f, "{}: {}", self.code, self.message)
30    }
31}
32
33impl std::error::Error for AppError {}
34
35pub type AppResult<T> = Result<T, AppError>;
36
37#[derive(Serialize)]
38struct ErrorEnvelope {
39    error: AppError,
40}