Skip to content

Commit

Permalink
Improve deserialization error message
Browse files Browse the repository at this point in the history
It now states that it was trying to deserialize a UUID, which was
unclear before.
  • Loading branch information
jplatte committed Dec 21, 2020
1 parent 7b34b27 commit de37bc9
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions src/serde_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ impl<'de> Deserialize<'de> for Uuid {
fn deserialize<D: Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
fn de_error<E: de::Error>(e: crate::Error) -> E {
E::custom(format_args!("UUID parsing failed: {}", e))
}

if deserializer.is_human_readable() {
struct UuidStringVisitor;

Expand All @@ -48,14 +52,14 @@ impl<'de> Deserialize<'de> for Uuid {
self,
value: &str,
) -> Result<Uuid, E> {
value.parse::<Uuid>().map_err(E::custom)
value.parse::<Uuid>().map_err(de_error)
}

fn visit_bytes<E: de::Error>(
self,
value: &[u8],
) -> Result<Uuid, E> {
Uuid::from_slice(value).map_err(E::custom)
Uuid::from_slice(value).map_err(de_error)
}
}

Expand All @@ -77,7 +81,7 @@ impl<'de> Deserialize<'de> for Uuid {
self,
value: &[u8],
) -> Result<Uuid, E> {
Uuid::from_slice(value).map_err(E::custom)
Uuid::from_slice(value).map_err(de_error)
}
}

Expand All @@ -88,31 +92,34 @@ impl<'de> Deserialize<'de> for Uuid {

#[cfg(test)]
mod serde_tests {
use serde_test;
use serde_test::{Compact, Configure, Readable, Token};

use crate::prelude::*;

#[test]
fn test_serialize_readable() {
use serde_test::Configure;

let uuid_str = "f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4";
let u = Uuid::parse_str(uuid_str).unwrap();
serde_test::assert_tokens(
&u.readable(),
&[serde_test::Token::Str(uuid_str)],
);
serde_test::assert_tokens(&u.readable(), &[Token::Str(uuid_str)]);
}

#[test]
fn test_serialize_compact() {
use serde_test::Configure;

let uuid_bytes = b"F9168C5E-CEB2-4F";
let u = Uuid::from_slice(uuid_bytes).unwrap();
serde_test::assert_tokens(
&u.compact(),
&[serde_test::Token::Bytes(uuid_bytes)],
serde_test::assert_tokens(&u.compact(), &[Token::Bytes(uuid_bytes)]);
}

#[test]
fn test_de_failure() {
serde_test::assert_de_tokens_error::<Readable<Uuid>>(
&[Token::Str("hello_world")],
"UUID parsing failed: invalid length: expected one of [36, 32], found 11",
);

serde_test::assert_de_tokens_error::<Compact<Uuid>>(
&[Token::Bytes(b"hello_world")],
"UUID parsing failed: invalid bytes length: expected 16, found 11",
);
}
}

0 comments on commit de37bc9

Please sign in to comment.