📌  相关文章
📜  422 (1)

📅  最后修改于: 2023-12-03 14:59:05.435000             🧑  作者: Mango

422 - Unprocessable Entity

The HTTP status code 422, also known as "Unprocessable Entity", is a client error response code indicating that the server understands the request syntax but was unable to process the provided data. It is typically used when the request contains semantically incorrect or incomprehensible data.

When to Use 422

The 422 status code is commonly used in the context of API development to indicate a client-side validation error. It indicates that the server was unable to process the request because the data provided in the request entity violates the server's business logic or validation rules. Some common scenarios where you might encounter a 422 status code include:

  1. Invalid data format: The request data does not adhere to the specified format or data type expected by the server.

  2. Missing required fields: The request is missing some mandatory fields or parameters required by the server.

  3. Data integrity issues: The request refers to data that cannot be found or has been deleted on the server.

  4. Business rule violations: The request violates certain business rules or constraints specified by the server.

Example Response
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": {
    "code": 422,
    "message": "Validation failed",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      },
      {
        "field": "password",
        "message": "Password must be at least 8 characters long"
      }
    ]
  }
}

In the example response above, the server returns a 422 status code with a JSON payload containing an error object. The error object provides additional details about the validation failures. Along with the generic error message, it includes an array of field-specific error messages and their corresponding field names.

Handling 422 Errors

When designing an API that returns a 422 status code, it is a good practice to include detailed error messages and field-specific error information whenever possible. This helps clients understand the exact nature of the validation failure and enables them to provide the correct data in subsequent requests.

To handle 422 errors when consuming an API, the client application should parse the response payload, extract the error details, and present appropriate messages to the end-user.

Conclusion

The 422 status code serves as an indicator of client-side validation errors. It informs the developer that the server understands the request but cannot process it due to invalid or inconsistent data. By returning rich error messages, you can provide meaningful feedback to developers or end-users and aid them in troubleshooting and resolving the issues.