lego_powered_up/
error.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use btleplug::api::ParseBDAddrError;
6use std::fmt::Display;
7
8#[derive(thiserror::Error, Debug)]
9pub enum Error {
10    #[error("Bluetooth error")]
11    BluetoothError(#[from] btleplug::Error),
12    #[error("NoneError: {0}")]
13    NoneError(String),
14    #[error("Parse error")]
15    ParseErrorBLE(#[from] ParseBDAddrError),
16    #[error("Timeout error: {0}")]
17    TimeoutError(String),
18    #[error("Parse error: {0}")]
19    ParseError(String),
20    #[error("Not implmented: {0}")]
21    NotImplementedError(String),
22    #[error("Hub error: {0}")]
23    HubError(String),
24}
25
26pub type Result<T> = std::result::Result<T, Error>;
27
28pub trait OptionContext<T> {
29    fn context<D: Display>(self, ctx: D) -> Result<T>;
30}
31
32impl<T> OptionContext<T> for Option<T> {
33    fn context<D: Display>(self, ctx: D) -> Result<T> {
34        self.ok_or_else(|| Error::NoneError(ctx.to_string()))
35    }
36}
37
38impl<T> OptionContext<T> for Result<T> {
39    fn context<D: Display>(self, _ctx: D) -> Result<T> {
40        self.map_err(Error::from)
41    }
42}