-
Notifications
You must be signed in to change notification settings - Fork 34
/
handle_error.rs
51 lines (46 loc) · 1.36 KB
/
handle_error.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use sonic_rs::{from_slice, from_str, Deserialize};
fn main() {
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct Foo {
a: Vec<i32>,
c: String,
}
// deal with Eof errors
let err = from_str::<Foo>("{\"a\": [").unwrap_err();
assert!(err.is_eof());
eprintln!("{}", err);
// EOF while parsing at line 1 column 6
// {"a": [
// ......^
assert_eq!(
format!("{}", err),
"EOF while parsing at line 1 column 6\n\n\t{\"a\": [\n\t......^\n"
);
// deal with unmatched type errors
let err = from_str::<Foo>("{ \"b\":[]}").unwrap_err();
eprintln!("{}", err);
assert!(err.is_unmatched_type());
// println as follows:
// missing field `a` at line 1 column 8
//
// { "b":[]}
// ........^
assert_eq!(
format!("{}", err),
"missing field `a` at line 1 column 8\n\n\t{ \"b\":[]}\n\t........^\n"
);
// deal with Syntax errors
let err = from_slice::<Foo>(b"{\"b\":\"\x80\"}").unwrap_err();
eprintln!("{}", err);
assert!(err.is_syntax());
// println as follows:
// Invalid UTF-8 characters in json at line 1 column 6
//
// {"b":"�"}
// ......^...
assert_eq!(
format!("{}", err),
"Invalid UTF-8 characters in json at line 1 column 6\n\n\t{\"b\":\"�\"}\n\t......^..\n"
);
}