Sub topic 9
Reading and handling serde errors
This chapter assumes you can write structs with #[derive(Deserialize)], call serde_json::from_str, and use Result with the ? operator. By the end you will know what kinds of errors serde produces, how to read their messages, and how to pass them through your own error types.
Where errors come from
Serde itself defines error traits (serde::de::Error and serde::ser::Error). It does not define one concrete error type. Each format crate supplies its own. With JSON, both directions return serde_json::Error.
serde_json::from_str,from_sliceandfrom_readerreturnResult<T, serde_json::Error>.serde_json::to_stringandto_writerreturn the same error type.- The
tomlcrate hastoml::de::Errorandtoml::ser::Error. Other format crates define their own as well.
Deserialization fails far more often than serialization, because the input comes from outside your program.
The four categories
serde_json::Error::classify() returns a Category. The category tells you whose fault the failure was.
| Category | Meaning | Typical cause |
|---|---|---|
| `Io` | Reading or writing failed | Broken file or socket passed to `from_reader` |
| `Syntax` | The text is not JSON | Trailing comma, unquoted key, plain text |
| `Eof` | The JSON stopped before it was complete | Truncated file or network body |
| `Data` | The JSON is valid but does not fit the type | Missing field, wrong type, unknown variant |
Syntax and Eof errors mean the input is damaged. Data errors mean the input is well formed but disagrees with your Rust type. That distinction often decides your response, for example HTTP 400 versus a retry.
Reading the messages
The next program feeds five inputs to one struct and prints the category, position and message for each failure.
use serde::Deserialize;
use serde_json::error::Category;
#[derive(Debug, Deserialize)]
struct User {
id: u32,
name: String,
}
fn main() {
let inputs = [
r#"{"id":1,"name":"Ada"}"#,
"not json",
r#"{"id":1}"#,
r#"{"id":"x","name":"Ada"}"#,
r#"{"id":1,"name":"Ada""#,
];
for input in inputs {
match serde_json::from_str::<User>(input) {
Ok(user) => println!("ok: {user:?}"),
Err(err) => {
let kind = match err.classify() {
Category::Io => "io",
Category::Syntax => "syntax",
Category::Data => "data",
Category::Eof => "eof",
};
println!("{kind} at {}:{}: {err}", err.line(), err.column());
}
}
}
}The failing lines print messages like these:
syntax at 1:1: expected value at line 1 column 1
data at 1:8: missing field `name` at line 1 column 8
data at 1:10: invalid type: string "x", expected u32 at line 1 column 10
eof at 1:21: EOF while parsing an object at line 1 column 21Exact column numbers can differ between serde_json versions, so treat them as approximate. The wording follows a pattern worth learning:
missing fieldnames a field the struct requires and the input lacks.invalid type: <what was found>, expected <what the type wanted>means the JSON value had the wrong kind.invalid valuemeans the kind was right but the value was not acceptable, such as-1for au32.unknown variantandunknown fieldlist the accepted names. The second appears only withdeny_unknown_fields.trailing charactersmeans a complete value was parsed and extra text followed it.
The position in a data error points to where the parser was when the mismatch was detected. For a missing field, that is the end of the object, not the place where the field should have been.
Errors you can trigger on purpose
Several attributes from earlier chapters change which errors appear.
- A missing
Option<T>field is not an error. It becomesNone. - A missing field with
#[serde(default)]takes the default. deny_unknown_fieldsturns extra keys intounknown fielderrors. Without it, extra keys are silently ignored.- An unknown enum variant name fails with
unknown variant. - An
#[serde(untagged)]enum fails withdata did not match any variant of untagged enum Name. This message does not say which variant came closest or why it failed. Prefer a tagged representation when you need useful error messages.
Serialization errors
Serializing can fail too, though less often. The usual cause is a data shape the format cannot express. JSON object keys must be strings, so a map keyed by a tuple fails.
use std::collections::HashMap;
fn main() {
let mut grid = HashMap::new();
grid.insert((1, 2), "wall");
match serde_json::to_string(&grid) {
Ok(json) => println!("{json}"),
Err(err) => println!("serialize failed: {err}"), // key must be a string
}
}For errors raised while serializing, line() and column() are both 0, since there is no input text to point into. A Mutex that was poisoned by a panic is another example of a serialization failure. A float that is NaN or infinite is not an error in serde_json. It is written as null.
Passing serde errors up through your own error type
Library and application code usually wraps the serde error so callers can match on it and still reach the original. The example below implements From<serde_json::Error> so that ? converts automatically, and source() so error-reporting tools can walk the chain.
use serde::Deserialize;
use std::error::Error;
use std::fmt;
#[derive(Debug, Deserialize)]
struct Settings {
port: u16,
}
#[derive(Debug)]
enum ConfigError {
Parse(serde_json::Error),
Invalid(String),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Parse(e) => write!(f, "could not parse config: {e}"),
ConfigError::Invalid(msg) => write!(f, "invalid config: {msg}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::Parse(e) => Some(e),
ConfigError::Invalid(_) => None,
}
}
}
impl From<serde_json::Error> for ConfigError {
fn from(e: serde_json::Error) -> Self {
ConfigError::Parse(e)
}
}
fn load(text: &str) -> Result<Settings, ConfigError> {
let settings: Settings = serde_json::from_str(text)?;
if settings.port == 0 {
return Err(ConfigError::Invalid("port must not be 0".to_string()));
}
Ok(settings)
}
fn main() {
for text in [r#"{"port":8080}"#, r#"{"port":0}"#, r#"{"port":70000}"#] {
match load(text) {
Ok(s) => println!("ok: {s:?}"),
Err(e) => println!("error: {e}"),
}
}
}The third input fails inside serde, because 70000 does not fit in a u16. The second input parses successfully, and your own check rejects it. Keeping the two kinds as separate variants lets callers tell a bad document from a bad value.
Raising your own errors from custom code
When you write a deserialize_with function or a manual Deserialize implementation, report problems with serde::de::Error::custom. The message is wrapped in the format's own error type, so it flows out through the same Result as built-in errors.
use serde::de::Error;
use serde::{Deserialize, Deserializer};
fn non_empty<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
let s = String::deserialize(deserializer)?;
if s.is_empty() {
Err(D::Error::custom("name must not be empty"))
} else {
Ok(s)
}
}
#[derive(Debug, Deserialize)]
struct Account {
#[serde(deserialize_with = "non_empty")]
name: String,
}
fn main() {
let err = serde_json::from_str::<Account>(r#"{"name":""}"#).unwrap_err();
println!("{err}");
println!("{:?}", err.classify());
}The printed message starts with your text and ends with a line and column. The category is Data, since the JSON itself was valid.
Gotchas
- Trailing input.
from_strrejects{"id":1} extrawithtrailing characters. To read several values from one stream, useserde_json::Deserializer::from_str(...).into_iter::<T>(). - No field path. A
serde_json::Errorreports a line and column but not the path, such asitems[3].price. For deeply nested input, the third-partyserde_path_to_errorcrate adds the path. - First error only. Deserialization stops at the first failure. You will not get a list of every problem in a document.
- Do not parse the message text. Use
classify()and theis_*helpers. The wording of messages can change between releases.
Exercise
A client posts the body {"id":1,"name":"Ada" (the closing brace is missing). Which Category does serde_json::from_str::<User> report, and should your service treat it as a retryable server problem or a bad request?
Show answer
It reports Category::Eof, because the input ended before the object was complete. The body is damaged, so the service should treat it as a bad request (for example HTTP 400). Retrying the same body will fail the same way. A truncated body can also mean the connection dropped, so the client may choose to resend.
Exercise
You add #[serde(deny_unknown_fields)] to a struct. What happens to the input {"id":1,"name":"Ada","age":36}, and which category does the error have?
Show answer
Deserialization fails with a message like "unknown field age, expected id or name". The category is Data, because the text is valid JSON that does not fit the type. Without the attribute, age would be ignored and the call would succeed.