2020-03-15 19:21:13 +01:00
# JSON decode errors
2022-03-06 01:43:10 +01:00
This example demonstrates how to return useful error messages to the client when the server receives a request with invalid JSON, or which cannot be deserialized to the expected model. By configuring an `error_handler` on the route, we can set appropriate response codes and return the string representation of the error.
2020-03-15 19:21:13 +01:00
## Usage
```shell
2021-10-06 23:28:53 +02:00
cd json/json_decode_error
2020-03-15 19:21:13 +01:00
cargo run
2022-03-06 01:41:32 +01:00
# Started HTTP server: 127.0.0.1:8080
2020-03-15 19:21:13 +01:00
```
## Examples
2022-03-06 01:43:10 +01:00
The examples use `curl -i` in order to show the status line with the response code. The response headers have been omitted for brevity, and replaced with an ellipsis `...` .
2020-03-15 19:21:13 +01:00
- A well-formed request
```shell
2022-03-06 01:41:32 +01:00
$ curl -i 127.0.0.1:8080 -H 'Content-Type: application/json' -d '{"name": "Alice"}'
2020-03-15 19:21:13 +01:00
HTTP/1.1 200 OK
...
2022-03-06 01:43:10 +01:00
Hello Alice!
2020-03-15 19:21:13 +01:00
```
- Missing `Content-Type` header
```shell
2022-03-06 01:41:32 +01:00
$ curl -i 127.0.0.1:8080 -d '{"name": "Bob"}'
2020-03-15 19:21:13 +01:00
HTTP/1.1 415 Unsupported Media Type
...
Content type error
```
- Malformed JSON
```shell
2022-03-06 01:41:32 +01:00
$ curl -i 127.0.0.1:8080 -H 'Content-Type: application/json' -d '{"name": "Eve}'
2020-03-15 19:21:13 +01:00
HTTP/1.1 400 Bad Request
...
Json deserialize error: EOF while parsing a string at line 1 column 14
```
- JSON value of wrong type
```shell
2022-03-06 01:41:32 +01:00
$ curl -i 127.0.0.1:8080 -H 'Content-Type: application/json' -d '{"name": 350}'
2020-03-15 19:21:13 +01:00
HTTP/1.1 422 Unprocessable Entity
...
Json deserialize error: invalid type: integer `350` , expected a string at line 1 column 12
```
- Wrong JSON key
```shell
2022-03-06 01:41:32 +01:00
$ curl -i 127.0.0.1:8080 -H 'Content-Type: application/json' -d '{"namn": "John"}'
2020-03-15 19:21:13 +01:00
HTTP/1.1 422 Unprocessable Entity
...
Json deserialize error: missing field `name` at line 1 column 16
```
## More documentation
[`actix_web::web::JsonConfig` ](https://docs.rs/actix-web/latest/actix_web/web/struct.JsonConfig.html )