HTTP error 422 is not as common as other codes such as 404 or 500. This particular error can be hard to diagnose as it doesn’t provide you with much information about what part of your request is causing the problem.
Broadly speaking, if you see an HTTP 422 error it means the server understands your request, but it can’t fulfill it due to a problem on your end. If you fix that problem, you should be able to reload the page and the error will go away.
In this article, we’ll talk about what causes the 422 error and how to troubleshoot it if you’re using WordPress. Let’s get to it!
Check Out Our Video Guide to the 422 Error
What Is the HTTP 422 Error?
Error 422 is an HTTP code that tells you that the server can’t process your request, although it understands it. The full name of the error code is 422 “unprocessable entity.”
In a nutshell, the error means that you’re making a request the server understands, but it can’t process it. Typically, this happens because there’s a semantic error somewhere in the request, usually within a PHP or JavaScript file.
Unlike other HTTP errors, the 422 code will keep reappearing until you manage to troubleshoot the problem with your request. However, this can be difficult since the error doesn’t provide specific information about what part of the request it can’t process.
What Causes the HTTP 422 Error?
Typically, the HTTP 422 code pops up when there’s a semantic error in the contents of a request. If you’re using WordPress, that usually means one of two things:
- One of the files involved in the request contains code with semantic errors. To put it another way, there’s an error somewhere in the code.
- You’re dealing with a corrupt database table.
One problem with error 422 is that there’s no way of knowing what its cause is at first glance. This means you may need to try more than one troubleshooting method until you arrive at the problem.
HTTP error 422 may not be as common as other codes such as 404 or 500- but don’t worry! 😅This guide is here to help 🚀Click to Tweet
You can check the HTTP response code of any page using our HTTP header Checker tool.
How To Fix the 422 Error in WordPress (2 Methods)
In this section, we’ll show you how to repair a corrupted WordPress database and how to identify files with semantic code errors. These steps will also help you debug other issues, such as the HTTP 400 error.
1. Repair a Corrupted WordPress Database
In some cases, tables within the WordPress database might become corrupted during an update. This means that if you’re updating a plugin, theme, or WordPress itself and the process is interrupted, database entries can start presenting errors.
A corrupt database can lead to all sorts of errors within WordPress, such as pages not loading, features not working correctly, and HTTP codes such as 422. There are two ways to repair a corrupted WordPress database. The easiest approach is to use a plugin such as WP-DBManager:
Once you activate WP-DBManager, you’ll get access to a new Database tab in the dashboard. Go to Database > Repair DB and select the tables that you want to repair. Since you may not know which table is corrupt, select them all and click on Repair:
The process should only take a few seconds and you’ll see a success message when it’s ready. Now, try accessing the page that returned the 422 error to see if it persists.
If you don’t have access to the WordPress admin due to the 422 error, you can repair the database manually. To do so, you’ll need to access the database from your hosting control panel.
If you use Kinsta, you can access the database from your MyKinsta dashboard. Select a website and go to the Info tab. Look for the Database access section, where you’ll find the login credentials for the database. Click on Open phpMyAdmin and enter those credentials:
Select the database you want to repair from the menu to the left and you’ll see a breakdown of all the tables it contains to the right. Use the Check all option at the bottom of the page to select every table. Then, look for the Repair table option in the menu to the right:
Click on the Go button and wait for phpMyAdmin to return a success message. Now, go ahead and check if the HTTP 422 error persists.
2. Use the WordPress Error Logs To Identify HTTP 422 Code Causes
If repairing the database doesn’t make error 422 go away, the problem lies with one of the WordPress files. Since every WordPress installation contains dozens to hundreds of files, it’s not feasible to check all of them for semantic code errors.
Your best bet, in this scenario, is to enable the WordPress debug feature, which will give you access to error logs. To enable the WordPress debug mode manually, you’ll need to edit the wp-config.php file in the root directory.
You can do that by accessing your website via a File Transfer Protocol (FTP) client and locating the wp-config.php file. Open the file and add the following two lines of code before the line that says /* That’s all, stop editing! Happy blogging. */:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
If the WP_DEBUG line already exists, make sure that it reads true and simply add the second line of code (the WP_DEBUG_LOG entry). Save the changes to the file and reload the page that returns the 422 error.
The error should persist, but now you have access to error logs. To read those logs, navigate to the wp-content folder inside the root directory and look for the debug.log file. You can open the file using a text editor.
If the file is new, it should only contain a few lines, one of which should refer to the error that’s causing the 422 code. The error should point you towards a specific file that’s causing the problem. It should also include information about which line within the file contains a semantic error.
If you use Kinsta, you don’t have to enable the WordPress debug mode or error logs manually. Instead, go to MyKinsta, select a website, and jump to the Tools tab. Inside you’ll find an option for enabling WordPress debugging:
After enabling debugging, you can go to the Logs tab and select the error.log option. MyKinsta will display the latest errors on your website and the viewer includes a search feature to help you find specific entries:
Focusing on the latest entries should help you identify which file is causing the 422 error. Once you identify the file, you can try and fix the semantic error or replace it with a stock version from WordPress.
Learn what causes what 422 error and how to troubleshoot it if you’re using WordPress, all in this guide 😄Click to Tweet
Summary
Identifying what’s causing the HTTP 422 error can be somewhat complicated. However, troubleshooting the error doesn’t take all that long. The process is much simpler if you’re using WordPress, as the software comes with tools that can help you when it comes to debugging errors.
If you run into the HTTP 422 error in WordPress, there are two ways that you can fix it:
- Repair a corrupted WordPress database.
- Use the WordPress error logs to identify the causes of the 422 code.
With Kinsta, troubleshooting errors is much easier. Our MyKinsta dashboard includes built-in tools for debugging WordPress. If you don’t want to troubleshoot issues manually, you can always reach out to our support team!
HTTP response status code 422 Unprocessable Entity is a client error that is returned by the server to indicate that it understands the content type, and the syntax is correct, but it is unable to process the instructions specified by the request.
Usage
When the 422 Unprocessable Entity error message is sent, the server is indicating that it cannot process the instructions contained in the request. The content type is understood, otherwise, a 415 Unsupported Media Type error will have been sent. Additionally, the syntax is valid, otherwise, a 400 Bad Request error will be more explanatory.
An error of this type can be generated if the request includes an XML instruction block as the message body, which is not only correctly formed but understood by the server, yet contains errors in logic that result in a server-side error.
Note
Search engines like Google will not index a URL with 422 Unprocessable Entity response status, and consequently, URLs that have been indexed in the past but are now returning this HTTP status code will be removed from the search results.
Example
In the example, the client uses an XML document to request that task #100
be started. The XML document is recognized and accepted by the server, and it is syntactically correct. For instance, it does not have an error such as an unmatched tag, nor does it contain a properly matched but unrecognized tag. However, the server does not have a record of a task with id=100. Therefore, the request cannot be processed.
Request
POST /requests HTTP/1.1
Host: www.example.ai
Content-Type: application/xml
Content-Length: 101
<?xml version="1.0" encoding="utf-8"?>
<request>
<id>100</id>
<action>start</action>
</request>
Response
HTTP/1.1 422 Unprocessable Entity
Content-Type: text/html
Content-Length: 150
<html>
<head>
<title>Request Failed</title>
</head>
<body>
<p>Task #100 is not recognized and cannot be started.</p>
</body>
</html>
Code references
.NET
HttpStatusCode.UnprocessableEntity
Rust
http::StatusCode::UNPROCESSABLE_ENTITY
Rails
:unprocessable_entity
Go
http.StatusUnprocessableEntity
Symfony
Response::HTTP_UNPROCESSABLE_ENTITY
Python3.5+
http.HTTPStatus.UNPROCESSABLE_ENTITY
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_UNPROCESSABLE_ENTITY
Angular
@angular/common/http/HttpStatusCode.UnprocessableEntity
Takeaway
The 422 Unprocessable Entity status code is a client error that is sent by the server to indicate that the request is syntactically correct and understood by the server, but semantically invalid.
See also
- RFC 4918
Last updated: June 2, 2022
400 Bad Request would now seem to be the best HTTP/1.1 status code for your use case.
At the time of your question (and my original answer), RFC 7231 was not a thing; at which point I objected to 400 Bad Request
because RFC 2616 said (with emphasis mine):
The request could not be understood by the server due to malformed syntax.
and the request you describe is syntactically valid JSON encased in syntactically valid HTTP, and thus the server has no issues with the syntax of the request.
However as pointed out by Lee Saferite in the comments, RFC 7231, which obsoletes RFC 2616, does not include that restriction:
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
However, prior to that re-wording (or if you want to quibble about RFC 7231 only being a proposed standard right now), 422 Unprocessable Entity
does not seem an incorrect HTTP status code for your use case, because as the introduction to RFC 4918 says:
While the status codes provided by HTTP/1.1 are sufficient to
describe most error conditions encountered by WebDAV methods, there
are some errors that do not fall neatly into the existing categories.
This specification defines extra status codes developed for WebDAV
methods (Section 11)
And the description of 422
says:
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions.
(Note the reference to syntax; I suspect 7231 partly obsoletes 4918 too)
This sounds exactly like your situation, but just in case there was any doubt, it goes on to say:
For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
(Replace «XML» with «JSON» and I think we can agree that’s your situation)
Now, some will object that RFC 4918 is about «HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)» and that you (presumably) are doing nothing involving WebDAV so shouldn’t use things from it.
Given the choice between using an error code in the original standard that explicitly doesn’t cover the situation, and one from an extension that describes the situation exactly, I would choose the latter.
Furthermore, RFC 4918 Section 21.4 refers to the IANA Hypertext Transfer Protocol (HTTP) Status Code Registry, where 422 can be found.
I propose that it is totally reasonable for an HTTP client or server to use any status code from that registry, so long as they do so correctly.
But as of HTTP/1.1, RFC 7231 has traction, so just use 400 Bad Request
!
Код состояния 422 (HTTP 422 Unprocessable Entity) обозначает ошибку со стороны пользователя, а не API. Сервер понимает запрос со стороны клиента и может работать с типом содержимого, который ему предоставили. Однако логическая ошибка делает выполнение невозможным.
Например, документ XML построен синтаксически грамотно, но со стороны семантики в инструкции содержится погрешность.
- вы отправляете полезные данные, которые недействительны в формате JSON;
- вы отправляете заголовки HTTP, такие как Content-Type или Accept, которые указывают значение, отличное от application / json;
- запрос может быть валиден по отношению к JSON, но что-то не так с содержимым. Например, указание API обновить кластер до несуществующего варианта;
- в теле или запросе содержится лишний символ или пробел (в первую очередь стоит проверить пробелы перед заголовком) или напротив, не хватает кавычек/проставлен неправильный тип. Самая актуальная проблема при работе с JSON, при которой может перестать работать весь код.
Проблема ошибка 422 через Ajax Post с использованием Laravel
В ajax этот код может выдаваться как ошибка по умолчанию, когда проверка не выполняется. Либо возвращаться Laravel при запросе, в котором допущена опечатка. Можно попробовать сделать запрос в консоли браузера: он должен выдать JSON с ошибками, возникшими во время проверки запроса. Есть вероятность, что код просто отправляет атрибуты формы не так, как вы запланировали. В любом случае, проблему решать программисту или вебмастеру.
Дополнительная информация
К сожалению, дать универсальный совет по исправлению ошибки 422 Unprocessable Entity непросто. Путь разрешения может сильно отличаться для каждой частной ситуации.
В первую очередь, попробуйте просмотреть свои данные и сделать запрос по вызывающему сомнения участку кода. Нужно убедиться, что вы правильно определили фрагмент данных, в котором содержится причина ошибки.
Если вы все еще не можете найти, где закралась ошибка 422 или вышеописанные способы не помогли выявить описанных причин сбоя функционирования, попробуйте спросить совет у общества веб-разработчиков, показав пример фрагмента вашего кода, чтобы узнать, могут ли другие определить, в чем проблема.
Дальше по теме…
The server understands the content type of the request entity (hence a 415 Unsupported Media Type status code is inappropriate), and the syntax of the request entity is correct (thus a 400 Bad Request status code is inappropriate) but was unable to process the contained instructions.
For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
- Source: RFC4918 Section 11.2
422 CODE REFERENCES
Rails HTTP Status Symbol :unprocessable_entity
Symfony HTTP Status Constant Response::HTTP_UNPROCESSABLE_ENTITY
.NET HttpStatusCode.UnprocessableEntity
Rust http::StatusCode::UNPROCESSABLE_ENTITY
Go http.StatusUnprocessableEntity
Python3.5+ http.HTTPStatus.UNPROCESSABLE_ENTITY
Apache HttpComponents Core org.apache.hc.core5.http.HttpStatus.SC_UNPROCESSABLE_ENTITY
Angular @angular/common/http/HttpStatusCode.UnprocessableEntity
422 status code example
Here’s an example request and response for a 422 Unprocessable Entity status code:
Request
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "",
"email": "example.com"
}
Response
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Unprocessable Entity",
"message": "Validation failed",
"details": [
{
"field": "name",
"message": "Name is required"
},
{
"field": "email",
"message": "Invalid email address"
}
]
}
In this example, the request is attempting to create a new user by sending a JSON payload to the server via a POST
request. However, the server is unable to process the request due to validation errors in the payload.
The server responds with a 422 Unprocessable Entity
status code and a JSON payload containing an error message, a description of the error, and details about the specific validation errors that occurred. The client can use this information to correct the errors and resubmit the request.
What causes a 422 status code?
A 422 status code is typically caused when a request is well-formed but the server is unable to process it because it contains semantic errors or does not meet certain conditions. Some common causes of a 422 status code include:
- Validation errors: The server is unable to process the request because the submitted data contains errors or is incomplete. For example, if a required field is missing or the data format is invalid.
- Business logic errors: The server is unable to fulfill the request because it violates some business rule or constraint. For example, if a user tries to register with an email address that is already in use.
- Authorization errors: The server is unable to process the request because the user is not authorized to perform the requested action. For example, if a user tries to delete a resource that they do not have permission to delete.
- Data conflicts: The server is unable to process the request because it conflicts with existing data. For example, if a user tries to update a resource that has been updated by another user in the meantime.
It is important to note that the exact cause of a 422 status code may vary depending on the specific application and its implementation.
How to fix a 422 status code
A 422 status code indicates that the server was unable to process the request because it contains invalid data. To fix a 422 status code, you need to identify the specific data that caused the issue and correct it. Here are some steps you can follow:
- Check the request payload: The 422 status code typically occurs when there is an issue with the request payload. Check the data being sent to the server and ensure that it is formatted correctly and is valid.
- Validate the input: Validate the input received by the server to ensure that it adheres to the defined structure and data types. If any of the input data is invalid, return a detailed error message to the client.
- Provide helpful error messages: Provide clear and informative error messages that can help the client identify the issue and correct it. This can help the client resolve the issue more quickly and minimize the number of 422 errors in the future.
- Test thoroughly: Ensure that your code is thoroughly tested to catch any validation errors or other issues that could cause a 422 status code.
By following these steps, you can fix the issues causing the 422 status code and ensure that the server is able to process the request successfully.
Additional resources
- Learn about web development
- Learn about SEO
- Web development services from WebFX
- SEO services from WebFX
- MDN Web Docs
- W3Schools
Return to List of HTTP Status Codes