Skip to content

Commit

Permalink
Add Error::io_error_kind
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jun 16, 2023
1 parent 136b773 commit 5d3116e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
50 changes: 49 additions & 1 deletion src/error.rs
@@ -1,6 +1,6 @@
//! When serializing or deserializing JSON goes wrong.

use crate::io;
use crate::io::{self, ErrorKind};
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use core::fmt::{self, Debug, Display};
Expand Down Expand Up @@ -105,6 +105,54 @@ impl Error {
pub fn is_eof(&self) -> bool {
self.classify() == Category::Eof
}

/// The kind reported by the underlying standard library I/O error, if this
/// error was caused by a failure to read or write bytes on an I/O stream.
///
/// # Example
///
/// ```
/// use serde_json::Value;
/// use std::io::{self, ErrorKind, Read};
/// use std::process;
///
/// struct ReaderThatWillTimeOut<'a>(&'a [u8]);
///
/// impl<'a> Read for ReaderThatWillTimeOut<'a> {
/// fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
/// if self.0.is_empty() {
/// Err(io::Error::new(ErrorKind::TimedOut, "timed out"))
/// } else {
/// self.0.read(buf)
/// }
/// }
/// }
///
/// fn main() {
/// let reader = ReaderThatWillTimeOut(br#" {"k": "#);
///
/// let _: Value = match serde_json::from_reader(reader) {
/// Ok(value) => value,
/// Err(error) => {
/// if error.io_error_kind() == Some(ErrorKind::TimedOut) {
/// // Maybe this application needs to retry certain kinds of errors.
///
/// # return;
/// } else {
/// eprintln!("error: {}", error);
/// process::exit(1);
/// }
/// }
/// };
/// }
/// ```
pub fn io_error_kind(&self) -> Option<ErrorKind> {
if let ErrorCode::Io(io_error) = &self.err.code {
Some(io_error.kind())
} else {
None
}
}
}

/// Categorizes the cause of a `serde_json::Error`.
Expand Down
4 changes: 4 additions & 0 deletions src/io/core.rs
Expand Up @@ -23,6 +23,10 @@ impl Error {
pub(crate) fn new(_kind: ErrorKind, _error: &'static str) -> Error {
Error
}

pub(crate) fn kind(&self) -> ErrorKind {
ErrorKind::Other
}
}

pub type Result<T> = result::Result<T, Error>;
Expand Down

0 comments on commit 5d3116e

Please sign in to comment.