ble_peripheral_rust/
error.rs1use std::{error, fmt};
2
3#[derive(Debug, Clone)]
4pub enum ErrorType {
5 Bluez,
6 CoreBluetooth,
7 Windows,
8 PermissionDenied,
9 ChannelError,
10}
11
12impl From<ErrorType> for &'static str {
13 fn from(error_type: ErrorType) -> &'static str {
14 match error_type {
15 ErrorType::Bluez => "Bluez",
16 ErrorType::CoreBluetooth => "CoreBluetooth",
17 ErrorType::Windows => "Windows",
18 ErrorType::PermissionDenied => "PermissionDenied",
19 ErrorType::ChannelError => "ChannelError",
20 }
21 }
22}
23
24impl fmt::Display for ErrorType {
25 fn fmt(self: &Self, f: &mut fmt::Formatter) -> fmt::Result {
26 let error_type: &str = self.clone().into();
27 write!(f, "<BlePeripheralRust {} Error>", error_type)
28 }
29}
30
31impl error::Error for ErrorType {}
32
33#[derive(Debug, Clone)]
34pub struct Error {
35 name: String,
36 description: String,
37 combined_description: String,
38 error_type: ErrorType,
39}
40
41impl Error {
42 pub fn new<T: Into<String>>(name: T, description: T, error_type: ErrorType) -> Self {
43 let name: String = name.into();
44 let description: String = description.into();
45 let combined_description = format!("{}: {}", name, description);
46 Error {
47 name,
48 description,
49 combined_description,
50 error_type,
51 }
52 }
53
54 pub fn from_type(error_type: ErrorType) -> Self {
55 let name: String = error_type.to_string();
56 let description: String = error_type.to_string();
57 let combined_description = format!("{}: {}", name, description);
58 Error {
59 name,
60 description,
61 combined_description,
62 error_type,
63 }
64 }
65
66 pub fn from_string(error: String, error_type: ErrorType) -> Self {
67 let name: String = error_type.to_string();
68 let description: String = error;
69 let combined_description = format!("{}: {}", name, description);
70 Error {
71 name,
72 description,
73 combined_description,
74 error_type,
75 }
76 }
77}
78
79impl fmt::Display for Error {
80 fn fmt(self: &Self, f: &mut fmt::Formatter) -> fmt::Result {
81 let error_type: &str = self.error_type.clone().into();
82 write!(
83 f,
84 "**BlePeripheralRust {} Error**\n\n\t{}:\n\t\t{}",
85 error_type, self.name, self.description,
86 )
87 }
88}
89
90impl error::Error for Error {
91 fn description(self: &Self) -> &str {
92 &self.combined_description
93 }
94
95 fn source(self: &Self) -> Option<&(dyn error::Error + 'static)> {
96 Some(&self.error_type)
97 }
98}