Skip to content

Commit b0c1afd

Browse files
committed
Add Error::io_error_kind
1 parent 136b773 commit b0c1afd

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/error.rs

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! When serializing or deserializing JSON goes wrong.
22
3-
use crate::io;
3+
use crate::io::{self, ErrorKind};
44
use alloc::boxed::Box;
55
use alloc::string::{String, ToString};
66
use core::fmt::{self, Debug, Display};
@@ -105,6 +105,54 @@ impl Error {
105105
pub fn is_eof(&self) -> bool {
106106
self.classify() == Category::Eof
107107
}
108+
109+
/// The kind reported by the underlying standard library I/O error, if this
110+
/// error was caused by a failure to read or write bytes on an I/O stream.
111+
///
112+
/// # Example
113+
///
114+
/// ```
115+
/// use serde_json::Value;
116+
/// use std::io::{self, ErrorKind, Read};
117+
/// use std::process;
118+
///
119+
/// struct ReaderThatWillTimeOut<'a>(&'a [u8]);
120+
///
121+
/// impl<'a> Read for ReaderThatWillTimeOut<'a> {
122+
/// fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
123+
/// if self.0.is_empty() {
124+
/// Err(io::Error::new(ErrorKind::TimedOut, "timed out"))
125+
/// } else {
126+
/// self.0.read(buf)
127+
/// }
128+
/// }
129+
/// }
130+
///
131+
/// fn main() {
132+
/// let reader = ReaderThatWillTimeOut(br#" {"k": "#);
133+
///
134+
/// let _: Value = match serde_json::from_reader(reader) {
135+
/// Ok(value) => value,
136+
/// Err(error) => {
137+
/// if error.io_error_kind() == Some(ErrorKind::TimedOut) {
138+
/// // Maybe this application needs to retry certain kinds of errors.
139+
///
140+
/// # return;
141+
/// } else {
142+
/// eprintln!("error: {}", error);
143+
/// process::exit(1);
144+
/// }
145+
/// }
146+
/// };
147+
/// }
148+
/// ```
149+
pub fn io_error_kind(&self) -> Option<ErrorKind> {
150+
if let ErrorCode::Io(io_error) = &self.err.code {
151+
Some(io_error.kind())
152+
} else {
153+
None
154+
}
155+
}
108156
}
109157

110158
/// Categorizes the cause of a `serde_json::Error`.

0 commit comments

Comments
 (0)