6

In Python, I can use marshmallow or Pydantic to validate user input just by defining a schema (much like a Rust struct). Then using that schema, Marshmallow loads the user input and returns the error it finds. Such as:

image

image

I can have custom error handle in actix-web by implementing ResponseError.

But, how can I return the description (position/field of invalid value) in a bad request body to the client?

image

azzamsa
  • 1,805
  • 2
  • 20
  • 28
  • I apologize for misleading you: my earlier comment said "don't post code as text" but I actually meant "post code as text, not *images*". (It was still early in the morning here, if that's an excuse...) Text is good. – trent Oct 10 '20 at 14:28

1 Answers1

18

I am always looking for answers.

Unfortunately, some web frameworks including actix handle JSON error before we can do any validation. I keep searching for using various keywords. One of them is "actix-web validate JSON" which leads me to many validator crates. But I get insight from this blog saying that:

Extractors are helpers that implement the FromRequest trait. In other words, they construct any object from a request and perform validation along the way. A handful of useful extractors are shipped with Actix web, such as JSON which uses serde_json to deserialize a JSON request body

So, I search for "actix Extractor" and bring me Extractor Doc and custom handling of extractor errors

So this snippet is taken from this boilerplate solves my current problem.

   App::new()
       .configure(health::init)
       .configure(students::init)
+      .app_data(web::JsonConfig::default().error_handler(|err, _req| {
+          error::InternalError::from_response(
+              "",
+              HttpResponse::BadRequest()
+                  .content_type("application/json")
+                  .body(format!(r#"{{"error":"{}"}}"#, err)),
+          )
+          .into()
+      }))

enter image description here

enter image description here

azzamsa
  • 1,805
  • 2
  • 20
  • 28
  • 1
    "format!(r#"{{"error":"{}"}}"#, err)" this does not escape the string. if err contains " or other "magic" json characters it will create an invalid json document – chpio Oct 12 '20 at 11:01
  • I just realized the same as QueryConfig for query params. Thx. – gzerone Sep 01 '22 at 10:06
  • Thank you for your answer @azzamsa. Is it possible to give details about the field where the type mismatch occured ? expected a string at line .... is not a great convenience for client consuming the api. I'd love to find a way to return for example "expected a string for firstname but got integer" – shellking4 Aug 18 '23 at 15:37