1
0
mirror of https://github.com/actix/examples synced 2024-11-30 17:14:35 +01:00
examples/json_decode_error
Stig Johan Berggren 8f3ce39d05
New example: Return JSON decode errors to a client (#268)
* Add JSON decode error example

* cargo fmt

* Use more appropriate response codes

* curl -i similar for all examples

* Add one more example of 422 response

* use to_string instead of empty format!
2020-03-16 03:21:13 +09:00
..
src New example: Return JSON decode errors to a client (#268) 2020-03-16 03:21:13 +09:00
Cargo.toml New example: Return JSON decode errors to a client (#268) 2020-03-16 03:21:13 +09:00
README.md New example: Return JSON decode errors to a client (#268) 2020-03-16 03:21:13 +09:00

JSON decode errors

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.

Usage

cd examples/json_decode_error
cargo run
# Started HTTP server: 127.0.0.1:8088

Examples

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 ....

  • A well-formed request

    $ curl -i 127.0.0.1:8088 -H 'Content-Type: application/json' -d '{"name": "Alice"}'
    HTTP/1.1 200 OK
    ...
    
    Hello Alice! 
    
  • Missing Content-Type header

    $ curl -i 127.0.0.1:8088 -d '{"name": "Bob"}'
    HTTP/1.1 415 Unsupported Media Type
    ...
    
    Content type error
    
  • Malformed JSON

    $ curl -i 127.0.0.1:8088 -H 'Content-Type: application/json' -d '{"name": "Eve}'
    HTTP/1.1 400 Bad Request
    ...
    
    Json deserialize error: EOF while parsing a string at line 1 column 14
    
  • JSON value of wrong type

    $ curl -i 127.0.0.1:8088 -H 'Content-Type: application/json' -d '{"name": 350}'
    HTTP/1.1 422 Unprocessable Entity
    ...
    
    Json deserialize error: invalid type: integer `350`, expected a string at line 1 column 12
    
  • Wrong JSON key

    $ curl -i 127.0.0.1:8088 -H 'Content-Type: application/json' -d '{"namn": "John"}'
    HTTP/1.1 422 Unprocessable Entity
    ...
    
    Json deserialize error: missing field `name` at line 1 column 16
    

More documentation

actix_web::web::JsonConfig