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");});Missing Request Body
Section titled “Missing Request Body”If the request body is empty, Mach returns:
400 Bad RequestThe request body is required.The endpoint is not executed.
Missing JSON Fields
Section titled “Missing JSON Fields”If a required JSON field is missing, Mach returns:
400 Bad RequestA required JSON field is missing.This happens during request body binding, before model validation runs.
Validation Failures
Section titled “Validation Failures”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:
usernameis shorter than 3 characters.emailis not a valid email address.ageis 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.