Skip to content
Download

Handling Validation Errors

When request body binding or validation fails, Mach returns a 400 Bad Request response before the endpoint handler runs.

Consider this model:

struct RegisterRequest {
std::string username;
std::string email;
int age;
void validate(mach::ValidationBuilder<RegisterRequest>& validation) const {
validation.field(&RegisterRequest::username)
.minLength(3)
.maxLength(30);
validation.field(&RegisterRequest::email).email();
validation.field(&RegisterRequest::age).min(18);
}
};
MACH_DEFINE_JSON(RegisterRequest, username, email, age)

and this endpoint:

app.mapPost("/register", [](RegisterRequest request) {
return mach::ok("Registration accepted");
});

If the request body is empty, Mach returns:

400 Bad Request
The request body is required.

The endpoint is not executed.

If a required JSON field is missing, Mach returns:

400 Bad Request
A required JSON field is missing.

This happens during request body binding, before model validation runs.

If the body can be bound successfully but one or more validation rules fail, Mach returns the validation errors together.

For example:

{
"username": "jd",
"email": "jordan.example.com",
"age": 16
}

This request fails all three validation rules:

  • username is shorter than 3 characters.
  • email is not a valid email address.
  • age is below the minimum of 18.

Mach returns:

{
"errors": [
"Value is too short",
"Invalid email format",
"Value is below the specified minimum"
]
}

with a 400 Bad Request status.

All three fields fail validation, and Mach reports all three errors in the same response.


You’ve now covered Mach’s validation workflow: defining validation rules, combining constraints, and understanding how invalid request bodies are rejected.