Skip to content

Commit 41953fe

Browse files
committed
refactor: use thiserror instead of failure
1 parent 6657c84 commit 41953fe

38 files changed

+903
-1176
lines changed

examples/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@ log = "0.4"
1414
futures = { version = "0.3", default-features = false, features = ["std", "async-await"] }
1515
env_logger = "0.9"
1616
hex = "0.4"
17-
failure = "0.1"
17+
thiserror = "1.0"
1818
rand = "0.8"
19+
anyhow = "1.0"
1920

2021
[dev-dependencies.tokio]
2122
version = "1.12"

examples/dht_server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ extern crate log;
77

88
use futures::future::FutureExt;
99
use futures::channel::mpsc;
10-
use failure::Error;
10+
use anyhow::Error;
1111
use rand::thread_rng;
1212

1313
use std::net::SocketAddr;

examples/echo.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ extern crate log;
99
use futures::{*, future::TryFutureExt};
1010
use futures::channel::mpsc;
1111
use hex::FromHex;
12-
use failure::{err_msg, Error};
12+
use anyhow::Error;
1313
use rand::thread_rng;
1414

1515
use std::net::SocketAddr;
@@ -174,7 +174,7 @@ async fn main() -> Result<(), Error> {
174174
Ok((_, share_relays)) =>
175175
friend_connections_c.handle_share_relays(pk, share_relays)
176176
.map_err(Error::from).await?,
177-
_ => return Err(err_msg("Failed to parse ShareRelays"))
177+
_ => return Err(Error::msg("Failed to parse ShareRelays"))
178178
}
179179
},
180180
0x18 => { // PACKET_ID_ONLINE

examples/onion_client.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ extern crate log;
33

44
use std::net::{SocketAddr, IpAddr};
55

6-
use failure::Error;
6+
use anyhow::Error;
77
use futures::future::FutureExt;
88
use futures::stream::StreamExt;
99
use futures::sink::SinkExt;
@@ -91,11 +91,14 @@ async fn main() -> Result<(), Error> {
9191
while let Some(event) = stream.next().await {
9292
let (packet, addr) = match event {
9393
Ok(ev) => ev,
94-
Err(ref e) => {
94+
Err(e) => {
9595
error!("packet receive error = {:?}", e);
9696

97-
if *e.kind() == DecodeErrorKind::Io { continue }
98-
else { unimplemented!() }
97+
if let DecodeError::Io(e) = e {
98+
return Err(Error::new(e));
99+
} else {
100+
continue;
101+
}
99102
}
100103
};
101104

examples/tcp_client.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use tox_core::relay::handshake::make_client_handshake;
99
use tox_core::relay::codec;
1010
use tox_core::stats::Stats;
1111

12-
use failure::{Error, err_msg};
12+
use anyhow::Error;
1313

1414
use hex::FromHex;
1515

@@ -81,7 +81,7 @@ async fn create_client(mut rx: mpsc::Receiver<Packet>, tx: mpsc::Sender<Packet>)
8181
tx.clone().send(Packet::PongResponse(
8282
PongResponse { ping_id: ping.ping_id }
8383
))
84-
.map_err(|_| err_msg("Could not send pong") )
84+
.map_err(|_| Error::msg("Could not send pong") )
8585
.await?;
8686
}
8787
}

examples/tcp_server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#[macro_use]
22
extern crate log;
33

4-
use failure::Error;
4+
use anyhow::Error;
55
use tox_crypto::*;
66
use tox_core::relay::server::{Server, tcp_run};
77
use tox_core::stats::Stats;

tox_core/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ log = "0.4"
2727
nom = "5.1"
2828
cookie-factory = "0.3"
2929
get_if_addrs = "0.5"
30-
failure = "0.1"
30+
thiserror = "1.0"
3131
lru = "0.6"
3232
bitflags = "1.3"
3333
itertools = "0.10"

tox_core/src/dht/codec.rs

Lines changed: 42 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -9,88 +9,74 @@ use crate::stats::*;
99

1010
use bytes::BytesMut;
1111
use cookie_factory::GenError;
12-
use failure::Fail;
12+
use thiserror::Error;
1313
use nom::{error::ErrorKind, Err};
1414
use tokio_util::codec::{Decoder, Encoder};
1515

1616
/// A serialized `Packet` should be not longer than 2048 bytes.
1717
pub const MAX_DHT_PACKET_SIZE: usize = 2048;
1818

19-
error_kind! {
20-
#[doc = "Error that can happen when decoding `Packet` from bytes."]
21-
#[derive(Debug)]
22-
DecodeError,
23-
#[doc = "Error that can happen when decoding `Packet` from bytes."]
24-
#[derive(Clone, Debug, Eq, PartialEq, Fail)]
25-
DecodeErrorKind {
26-
#[doc = "Error indicates that we received too big packet."]
27-
#[fail(display = "Packet should not be longer than 2048 bytes: {} bytes", len)]
28-
TooBigPacket {
29-
#[doc = "Length of received packet."]
30-
len: usize
31-
},
32-
#[doc = "Error indicates that received packet can't be parsed."]
33-
#[fail(display = "Deserialize Packet error: {:?}, packet: {:?}", error, packet)]
34-
Deserialize {
35-
#[doc = "Parsing error."]
36-
error: nom::Err<(Vec<u8>, ErrorKind)>,
37-
#[doc = "Received packet."]
38-
packet: Vec<u8>,
39-
},
40-
#[doc = "General IO error that can happen with UDP socket."]
41-
#[fail(display = "IO Error")]
42-
Io,
43-
}
19+
/// Error that can happen when decoding `Packet` from bytes.
20+
#[derive(Debug, Error)]
21+
pub enum DecodeError {
22+
/// Error indicates that we received too big packet.
23+
#[error("Packet should not be longer than 2048 bytes: {} bytes", len)]
24+
TooBigPacket {
25+
/// Length of received packet.
26+
len: usize
27+
},
28+
/// Error indicates that received packet can't be parsed.
29+
#[error("Deserialize Packet error: {:?}, packet: {:?}", error, packet)]
30+
Deserialize {
31+
/// Parsing error.
32+
error: nom::Err<(Vec<u8>, ErrorKind)>,
33+
/// Received packet.
34+
packet: Vec<u8>,
35+
},
36+
/// General IO error that can happen with UDP socket.
37+
#[error("IO Error")]
38+
Io(IoError),
4439
}
4540

4641
impl DecodeError {
4742
pub(crate) fn too_big_packet(len: usize) -> DecodeError {
48-
DecodeError::from(DecodeErrorKind::TooBigPacket { len })
43+
DecodeError::TooBigPacket { len }
4944
}
5045

5146
pub(crate) fn deserialize(e: Err<(&[u8], ErrorKind)>, packet: Vec<u8>) -> DecodeError {
52-
DecodeError::from(DecodeErrorKind::Deserialize { error: e.to_owned(), packet })
47+
DecodeError::Deserialize { error: e.to_owned(), packet }
5348
}
5449
}
5550

56-
error_kind! {
57-
#[doc = "Error that can happen when encoding `Packet` to bytes."]
58-
#[derive(Debug)]
59-
EncodeError,
60-
#[doc = "Error that can happen when encoding `Packet` to bytes."]
61-
#[derive(Debug, Fail)]
62-
EncodeErrorKind {
63-
#[doc = "Error indicates that `Packet` is invalid and can't be serialized."]
64-
#[fail(display = "Serialize Packet error: {:?}", error)]
65-
Serialize {
66-
#[doc = "Serialization error."]
67-
error: GenError
68-
},
69-
#[doc = "General IO error that can happen with UDP socket."]
70-
#[fail(display = "IO Error")]
71-
Io,
72-
}
51+
/// Error that can happen when encoding `Packet` to bytes.
52+
#[derive(Debug, Error)]
53+
pub enum EncodeError {
54+
/// Error indicates that `Packet` is invalid and can't be serialized.
55+
#[error("Serialize Packet error: {:?}", error)]
56+
Serialize {
57+
/// Serialization error.
58+
error: GenError
59+
},
60+
/// General IO error that can happen with UDP socket.
61+
#[error("IO Error")]
62+
Io(IoError),
7363
}
7464

7565
impl EncodeError {
7666
pub(crate) fn serialize(error: GenError) -> EncodeError {
77-
EncodeError::from(EncodeErrorKind::Serialize { error })
67+
EncodeError::Serialize { error }
7868
}
7969
}
8070

8171
impl From<IoError> for DecodeError {
8272
fn from(error: IoError) -> DecodeError {
83-
DecodeError {
84-
ctx: error.context(DecodeErrorKind::Io)
85-
}
73+
DecodeError::Io(error)
8674
}
8775
}
8876

8977
impl From<IoError> for EncodeError {
9078
fn from(error: IoError) -> EncodeError {
91-
EncodeError {
92-
ctx: error.context(EncodeErrorKind::Io)
93-
}
79+
EncodeError::Io(error)
9480
}
9581
}
9682

@@ -340,9 +326,8 @@ mod tests {
340326
buf.extend_from_slice(b"\xFF");
341327

342328
let res = codec.decode(&mut buf);
343-
// not enought bytes to decode EncryptedPacket
344-
let error = res.err().unwrap();
345-
assert_eq!(*error.kind(), DecodeErrorKind::Deserialize { error: Err::Error((vec![255], ErrorKind::Alt)) , packet: vec![0xff] });
329+
// not enough bytes to decode EncryptedPacket
330+
assert!(matches!(res, Err(DecodeError::Deserialize { error: Err::Error((_, ErrorKind::Alt)), packet: _ })));
346331
}
347332

348333
#[test]
@@ -372,9 +357,8 @@ mod tests {
372357
let res = codec.encode(packet, &mut buf);
373358
assert!(res.is_err());
374359
let error = res.err().unwrap();
375-
let error_kind = error.kind();
376-
let error_serialize = unpack!(error_kind, EncodeErrorKind::Serialize, error);
360+
let error_serialize = unpack!(error, EncodeError::Serialize, error);
377361
let too_small = unpack!(error_serialize, GenError::BufferTooSmall);
378-
assert_eq!(*too_small, 2106 - MAX_DHT_PACKET_SIZE);
362+
assert_eq!(too_small, 2106 - MAX_DHT_PACKET_SIZE);
379363
}
380364
}

tox_core/src/dht/daemon_state.rs

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,30 +14,25 @@ use tox_binary_io::*;
1414
use crate::dht::kbucket::*;
1515
use crate::dht::ktree::*;
1616

17-
use failure::Fail;
17+
use thiserror::Error;
1818
use nom::{Err, error::ErrorKind as NomErrorKind};
1919

20-
error_kind! {
21-
#[doc = "An error that can occur while serializing/deserializing object."]
22-
#[derive(Debug)]
23-
DeserializeError,
24-
#[doc = "The specific kind of error that can occur."]
25-
#[derive(Clone, Debug, Eq, PartialEq, Fail)]
26-
DeserializeErrorKind {
27-
#[doc = "Error indicates that object can't be parsed."]
28-
#[fail(display = "Deserialize object error: {:?}, data: {:?}", error, data)]
29-
Deserialize {
30-
#[doc = "Parsing error."]
31-
error: nom::Err<(Vec<u8>, NomErrorKind)>,
32-
#[doc = "Object serialized data."]
33-
data: Vec<u8>,
34-
},
35-
}
20+
/// An error that can occur while serializing/deserializing object.
21+
#[derive(Clone, Debug, Eq, PartialEq, Error)]
22+
pub enum DeserializeError {
23+
/// Error indicates that object can't be parsed.
24+
#[error("Deserialize object error: {:?}, data: {:?}", error, data)]
25+
Deserialize {
26+
/// Parsing error.
27+
error: nom::Err<(Vec<u8>, NomErrorKind)>,
28+
/// Object serialized data.
29+
data: Vec<u8>,
30+
},
3631
}
3732

3833
impl DeserializeError {
3934
pub(crate) fn deserialize(e: Err<(&[u8], NomErrorKind)>, data: Vec<u8>) -> DeserializeError {
40-
DeserializeError::from(DeserializeErrorKind::Deserialize { error: e.to_owned(), data })
35+
DeserializeError::Deserialize { error: e.to_owned(), data }
4136
}
4237
}
4338

@@ -143,14 +138,14 @@ mod tests {
143138
let error = res.err().unwrap();
144139
let mut input = vec![2, 1, 2, 3, 4, 4, 210];
145140
input.extend_from_slice(&pk_org.as_bytes()[..crypto_box::KEY_SIZE - 1]);
146-
assert_eq!(*error.kind(), DeserializeErrorKind::Deserialize { error: Err::Error((
141+
assert_eq!(error, DeserializeError::Deserialize { error: Err::Error((
147142
input, NomErrorKind::Eof)), data: serialized_vec[..serialized_len - 1].to_vec() });
148143

149144
// test with serialized data corrupted
150145
let serialized_vec = [42; 10];
151146
let res = DaemonState::deserialize_old(&alice, &serialized_vec).await;
152147
let error = res.err().unwrap();
153-
assert_eq!(*error.kind(), DeserializeErrorKind::Deserialize { error: Err::Error((
148+
assert_eq!(error, DeserializeError::Deserialize { error: Err::Error((
154149
vec![42; 10], NomErrorKind::Tag)), data: serialized_vec.to_vec() });
155150

156151
// test with empty close list

tox_core/src/dht/lan_discovery.rs

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,27 @@
22
33
use std::iter;
44
use std::net::{IpAddr, SocketAddr};
5-
use std::time::{Duration};
5+
use std::time::Duration;
66

7-
use failure::Fail;
7+
use thiserror::Error;
88
use futures::{stream, SinkExt};
99
use futures::channel::mpsc;
1010
use get_if_addrs::IfAddr;
1111

12+
use tokio::time::error::Elapsed;
1213
use tox_crypto::*;
1314
use tox_packet::dht::*;
1415

15-
error_kind! {
16-
#[doc = "Error that can happen during lan discovery."]
17-
#[derive(Debug)]
18-
LanDiscoveryError,
19-
#[doc = "The specific kind of error that can occur."]
20-
#[derive(Debug, Eq, PartialEq, Fail)]
21-
LanDiscoveryErrorKind {
22-
#[doc = "Ping wakeup timer error"]
23-
#[fail(display = "Lan discovery wakeup timer error.")]
24-
Wakeup,
25-
#[doc = "Send packet(s) error."]
26-
#[fail(display = "Send packet(s) error")]
27-
SendTo,
28-
}
16+
17+
/// Error that can happen during lan discovery.
18+
#[derive(Debug, PartialEq, Error)]
19+
pub enum LanDiscoveryError {
20+
/// Ping wakeup timer error
21+
#[error("Lan discovery wakeup timer error.")]
22+
Wakeup,
23+
/// Send packet(s) time out.
24+
#[error("Send packet(s) error")]
25+
Timeout(Elapsed),
2926
}
3027

3128
/// How many ports should be used on every iteration.
@@ -150,7 +147,7 @@ impl LanDiscoverySender {
150147
if let Err(e) = tokio::time::timeout(interval, self.send()).await {
151148
warn!("Failed to send LAN discovery packets: {}", e);
152149

153-
return Err(e.context(LanDiscoveryErrorKind::SendTo).into())
150+
return Err(LanDiscoveryError::Timeout(e))
154151
}
155152
}
156153
}

0 commit comments

Comments
 (0)