rseip/
error.rs

1// rseip
2//
3// rseip - Ethernet/IP (CIP) in pure Rust.
4// Copyright: 2021, Joylei <leingliu@gmail.com>
5// License: MIT
6
7use crate::client::ab_eip::PathError;
8use core::fmt;
9use rseip_core::{Error, String};
10use std::io;
11
12/// client error
13#[derive(Debug)]
14pub enum ClientError {
15    Io { kind: &'static str, err: io::Error },
16    Custom { kind: &'static str, msg: String },
17}
18
19impl ClientError {
20    pub fn kind(&self) -> &'static str {
21        match self {
22            Self::Io { kind, .. } => kind,
23            Self::Custom { kind, .. } => kind,
24        }
25    }
26
27    pub fn kind_mut(&mut self) -> &mut &'static str {
28        match self {
29            Self::Io { kind, .. } => kind,
30            Self::Custom { kind, .. } => kind,
31        }
32    }
33}
34
35impl std::error::Error for ClientError {}
36
37impl fmt::Display for ClientError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Self::Io { kind, err } => write!(f, "{} - {}", kind, err),
41            Self::Custom { kind, msg } => write!(f, "{} - {}", kind, msg),
42        }
43    }
44}
45
46impl Error for ClientError {
47    fn with_kind(mut self, kind: &'static str) -> Self {
48        *self.kind_mut() = kind;
49        self
50    }
51
52    fn custom<T: core::fmt::Display>(msg: T) -> Self {
53        Self::Custom {
54            kind: "custom",
55            msg: msg.to_string().into(),
56        }
57    }
58}
59
60impl From<io::Error> for ClientError {
61    fn from(e: io::Error) -> Self {
62        Self::Io { kind: "io", err: e }
63    }
64}
65
66impl From<PathError> for ClientError {
67    fn from(e: PathError) -> Self {
68        Self::custom(e).with_kind("tag path error")
69    }
70}