pancake_db_client/
errors.rs

1use std::fmt;
2use std::fmt::{Display, Formatter};
3use std::string::FromUtf8Error;
4
5use tonic::{Code, Status};
6
7trait OtherUpcastable: std::error::Error {}
8impl OtherUpcastable for FromUtf8Error {}
9#[cfg(feature = "read")]
10impl OtherUpcastable for pancake_db_core::errors::CoreError {}
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct ClientError {
14  pub message: String,
15  pub kind: ClientErrorKind,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub enum ClientErrorKind {
20  Connection,
21  Grpc {
22    code: Code,
23  },
24  Other,
25}
26
27impl Display for ClientErrorKind {
28  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
29    let s = match &self {
30      ClientErrorKind::Connection => "connection error".to_string(),
31      ClientErrorKind::Grpc { code } => format!("GRPC error {}", code),
32      ClientErrorKind::Other => "client-side error".to_string(),
33    };
34    f.write_str(&s)
35  }
36}
37
38impl ClientError {
39  pub fn other(message: String) -> Self {
40    ClientError {
41      message,
42      kind: ClientErrorKind::Other,
43    }
44  }
45}
46
47impl Display for ClientError {
48  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
49    write!(
50      f,
51      "PancakeDB {}, message: {}",
52      self.kind,
53      self.message,
54    )
55  }
56}
57
58impl<T> From<T> for ClientError where T: OtherUpcastable {
59  fn from(e: T) -> ClientError {
60    ClientError {
61      message: e.to_string(),
62      kind: ClientErrorKind::Other,
63    }
64  }
65}
66
67impl From<tonic::transport::Error> for ClientError {
68  fn from(err: tonic::transport::Error) -> Self {
69    ClientError {
70      message: err.to_string(),
71      kind: ClientErrorKind::Connection,
72    }
73  }
74}
75
76impl From<Status> for ClientError {
77  fn from(status: Status) -> Self {
78    ClientError {
79      message: status.message().to_string(),
80      kind: ClientErrorKind::Grpc { code: status.code(), },
81    }
82  }
83}
84
85impl std::error::Error for ClientError {}
86
87pub type ClientResult<T> = Result<T, ClientError>;