Skip to content

Commit 9e02a02

Browse files
committed
wip: Impl Error for FlakeGenErr
1 parent 339989f commit 9e02a02

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/gen.rs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::{error::Error, fmt::Display};
2+
13
use mac_address::{get_mac_address, MacAddress, MacAddressError};
24

35
use crate::{id::Flake, seq::SeqGen};
@@ -35,7 +37,11 @@ impl FlakeGen {
3537
/// let id: Flake = gen.next().expect("No ID was generated");
3638
/// ```
3739
pub fn with_mac_addr() -> Result<FlakeGen, FlakeGenErr> {
38-
let mac_addr: MacAddress = get_mac_address()?.ok_or(FlakeGenErr::NoMacAddr)?;
40+
let mac_addr: MacAddress = match get_mac_address() {
41+
Ok(Some(addr)) => addr,
42+
Ok(None) => return Err(FlakeGenErr::NoMacAddr(None)),
43+
Err(err) => return Err(FlakeGenErr::NoMacAddr(Some(err))),
44+
};
3945
let mac_addr: u64 =
4046
mac_addr.bytes().iter().fold(0u64, |acc, value| (acc << 8) + (*value as u64));
4147

@@ -82,15 +88,34 @@ impl Iterator for FlakeGen {
8288
pub enum FlakeGenErr {
8389
/// No MAC address could be found on the host device, which makes it impossible to generate
8490
/// flake ids that are globally unique.
85-
NoMacAddr,
91+
NoMacAddr(Option<MacAddressError>),
92+
}
93+
94+
impl Display for FlakeGenErr {
95+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96+
f.write_str("unable to acquire MAC address")
97+
}
8698
}
8799

88-
impl From<MacAddressError> for FlakeGenErr {
89-
fn from(_: MacAddressError) -> Self {
90-
FlakeGenErr::NoMacAddr
100+
impl Error for FlakeGenErr {
101+
fn source(&self) -> Option<&(dyn Error + 'static)> {
102+
match self {
103+
FlakeGenErr::NoMacAddr(Some(err)) => Some(err),
104+
FlakeGenErr::NoMacAddr(None) => None,
105+
}
106+
}
107+
108+
fn cause(&self) -> Option<&dyn Error> {
109+
self.source()
91110
}
92111
}
93112

113+
// impl From<MacAddressError> for FlakeGenErr {
114+
// fn from(err: MacAddressError) -> Self {
115+
// FlakeGenErr::NoMacAddr(Some(err))
116+
// }
117+
// }
118+
94119
/// A FlakeErr is an error that could happen when we try to generate an _identifier_ (`Flake`)
95120
#[derive(Debug)]
96121
pub enum FlakeErr {

0 commit comments

Comments
 (0)