Mock 422 Unprocessable Entity Response
Generate a 422 Unprocessable Entity error response with detailed validation errors. Common in Laravel, Rails, and other frameworks.
Detailed Explanation
422 Unprocessable Entity
The 422 status code indicates that the server understands the content type and syntax of the request, but the data is semantically invalid. It is commonly used by frameworks like Laravel and Ruby on Rails for validation errors.
Response Structure
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email field is required.",
"The email must be a valid email address."
],
"password": [
"The password must be at least 8 characters.",
"The password must contain at least one uppercase letter."
],
"age": [
"The age must be a number.",
"The age must be between 18 and 120."
]
}
}
400 vs 422
| Aspect | 400 Bad Request | 422 Unprocessable Entity |
|---|---|---|
| Syntax | Malformed JSON, wrong Content-Type | Valid JSON, correct syntax |
| Semantics | N/A (couldn't parse) | Fields present but values invalid |
| Common in | Express, Fastify | Laravel, Rails, Phoenix |
| RFC | HTTP/1.1 | WebDAV (RFC 4918) |
Field-Grouped Errors
This pattern groups errors by field name, with each field having an array of error messages. This is particularly useful for:
- Displaying multiple errors per field
- Programmatically highlighting all invalid fields
- Supporting internationalized error messages
Frontend Integration
Most form libraries (React Hook Form, Formik, VeeValidate) have built-in support for setting field-level errors. Map the response errors object directly to the form state:
Object.entries(response.errors).forEach(([field, messages]) => {
setError(field, { message: messages[0] });
});
Use Case
Developers working with Laravel, Rails, or similar frameworks can use this mock to test their frontend's handling of 422 validation errors, ensuring proper field-level error display and form state management.