|
1 | 1 | //! When serializing or deserializing JSON goes wrong.
|
2 | 2 |
|
3 |
| -use crate::io; |
| 3 | +use crate::io::{self, ErrorKind}; |
4 | 4 | use alloc::boxed::Box;
|
5 | 5 | use alloc::string::{String, ToString};
|
6 | 6 | use core::fmt::{self, Debug, Display};
|
@@ -105,6 +105,54 @@ impl Error {
|
105 | 105 | pub fn is_eof(&self) -> bool {
|
106 | 106 | self.classify() == Category::Eof
|
107 | 107 | }
|
| 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 | + } |
108 | 156 | }
|
109 | 157 |
|
110 | 158 | /// Categorizes the cause of a `serde_json::Error`.
|
|
0 commit comments