1use serde::ser::SerializeStruct;
2use serde::{Serialize, Serializer};
3use std::fmt::Display;
4use std::num::ParseIntError;
5use std::string::FromUtf8Error;
6
7#[derive(Debug, Clone)]
8pub enum Error {
9 InvalidUtf8(String),
10 ParseIntError(String),
11 CliError(String),
12 IOError(String),
13}
14
15impl Serialize for Error {
16 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
17 where
18 S: serde::Serializer,
19 {
20 let mut s = serializer.serialize_struct("Error", 2)?;
21 s.serialize_field("variant", &self.variant())?;
22 s.serialize_field("message", &format!("{}", self))?;
23 s.end()
24 }
25}
26impl Display for Error {
27 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
28 write!(
29 f,
30 "{}{}",
31 self.variant(),
32 match self {
33 Self::InvalidUtf8(e) => e.to_string(),
34 Self::ParseIntError(e) => e.to_string(),
35 Self::CliError(e) => e.to_string(),
36 Self::IOError(e) => e.to_string(),
37 }
38 )
39 }
40}
41
42impl Error {
43 pub fn variant(&self) -> String {
44 match self {
45 Error::InvalidUtf8(_) => "InvalidUtf8",
46 Error::ParseIntError(_) => "ParseIntError",
47 Error::CliError(_) => "CliError",
48 Error::IOError(_) => "IOError",
49 }
50 .to_string()
51 }
52}
53
54impl std::error::Error for Error {}
55impl From<ParseIntError> for Error {
56 fn from(e: ParseIntError) -> Self {
57 Error::ParseIntError(format!("{}", e))
58 }
59}
60impl From<String> for Error {
61 fn from(e: String) -> Self {
62 Error::CliError(e)
63 }
64}
65impl From<FromUtf8Error> for Error {
66 fn from(e: FromUtf8Error) -> Self {
67 Error::InvalidUtf8(format!("{}", e))
68 }
69}
70impl From<std::io::Error> for Error {
71 fn from(e: std::io::Error) -> Self {
72 Error::IOError(format!("{}", e))
73 }
74}
75impl From<iocore::Error> for Error {
76 fn from(e: iocore::Error) -> Self {
77 Error::IOError(format!("{}", e))
78 }
79}
80pub type Result<T> = std::result::Result<T, Error>;