Skip to content

Commit 4167c56

Browse files
author
Minh Vu
authored
codec: expose I/O sources from codec errors (#8665)
1 parent cdd9dae commit 4167c56

3 files changed

Lines changed: 49 additions & 2 deletions

File tree

‎tokio-util/src/codec/any_delimiter_codec.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,4 +259,11 @@ impl From<io::Error> for AnyDelimiterCodecError {
259259
}
260260
}
261261

262-
impl std::error::Error for AnyDelimiterCodecError {}
262+
impl std::error::Error for AnyDelimiterCodecError {
263+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
264+
match self {
265+
Self::Io(err) => Some(err),
266+
Self::MaxChunkLengthExceeded => None,
267+
}
268+
}
269+
}

‎tokio-util/src/codec/lines_codec.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,4 +226,11 @@ impl From<io::Error> for LinesCodecError {
226226
}
227227
}
228228

229-
impl std::error::Error for LinesCodecError {}
229+
impl std::error::Error for LinesCodecError {
230+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
231+
match self {
232+
Self::Io(err) => Some(err),
233+
Self::MaxLineLengthExceeded => None,
234+
}
235+
}
236+
}

‎tokio-util/tests/codecs.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,3 +499,36 @@ fn any_delimiter_encoder() {
499499
codec.encode("chunk 2", &mut buf).unwrap();
500500
assert_eq!("chunk 1;--;chunk 2;--;", buf);
501501
}
502+
503+
#[test]
504+
fn codec_error_sources() {
505+
use std::error::Error;
506+
use std::io::{self, ErrorKind};
507+
use tokio_util::codec::{AnyDelimiterCodecError, LinesCodecError};
508+
509+
let lines_error = LinesCodecError::from(io::Error::from(ErrorKind::BrokenPipe));
510+
assert_eq!(
511+
lines_error
512+
.source()
513+
.unwrap()
514+
.downcast_ref::<io::Error>()
515+
.unwrap()
516+
.kind(),
517+
ErrorKind::BrokenPipe
518+
);
519+
assert!(LinesCodecError::MaxLineLengthExceeded.source().is_none());
520+
521+
let delimiter_error = AnyDelimiterCodecError::from(io::Error::from(ErrorKind::TimedOut));
522+
assert_eq!(
523+
delimiter_error
524+
.source()
525+
.unwrap()
526+
.downcast_ref::<io::Error>()
527+
.unwrap()
528+
.kind(),
529+
ErrorKind::TimedOut
530+
);
531+
assert!(AnyDelimiterCodecError::MaxChunkLengthExceeded
532+
.source()
533+
.is_none());
534+
}

0 commit comments

Comments
 (0)