cp_microservice/core/
error.rs1use std::fmt;
2
3use async_channel::{RecvError, SendError};
4use serde::{Deserialize, Serialize};
5use tokio::time::error::Elapsed;
6
7#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
8pub enum ErrorKind {
9 ApiError,
10 LogicError,
11 StorageError,
12 RequestError,
13 Unknown,
14 InitializationError,
15 InternalError,
16}
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19pub struct Error {
20 pub kind: ErrorKind,
21 pub message: String,
22}
23
24impl Error {
25 pub fn new(kind: ErrorKind, message: impl Into<String>) -> Error {
26 Error {
27 kind,
28 message: message.into(),
29 }
30 }
31
32 pub fn kind(&self) -> ErrorKind {
33 self.kind
34 }
35}
36
37impl fmt::Display for Error {
38 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 write!(f, "{}", self.message)
40 }
41}
42
43impl From<Elapsed> for Error {
44 fn from(value: Elapsed) -> Self {
45 Self::new(ErrorKind::InternalError, format!("timed out: {}", &value))
46 }
47}
48
49impl From<std::io::Error> for Error {
50 fn from(value: std::io::Error) -> Self {
51 Self::new(ErrorKind::InternalError, format!("{}", &value))
52 }
53}
54
55impl<T> From<SendError<T>> for Error {
56 fn from(value: SendError<T>) -> Self {
57 Self::new(
58 ErrorKind::InternalError,
59 format!("failed to send request: {}", &value),
60 )
61 }
62}
63
64impl From<RecvError> for Error {
65 fn from(value: RecvError) -> Self {
66 Self::new(
67 ErrorKind::InternalError,
68 format!("failed to receive request: {}", &value),
69 )
70 }
71}