If you ever tried to access a website and got a "404, error not found" message, then you have an idea of what http status codes are.
Http status codes are issued by a server in response to a request from a client to said server. There are many status codes and they can be categorized between 1xx and 5xx, this means there are error codes in 100's, some in 200's, some 300's, 400's and 500's. The most common one's however are 200 , 201, 400, 403, 404 and 500. You can find more about the http codes here.
The aim of this article is to explain the difference between error 400(4xx) and error 500(5xx) and to help you understand when and when not to use them.
Its easy to use either of both error codes interchangeably but it should not be so, even though they are similar, they have different use cases. The major difference between them is whose fault the error is and I would explain. A 4xx error indicates that the error/fault is from the user while a 5xx error indicates that the fault is from the server.
An example is a user input form, a lot of forms have an asterisk beside a field to specify the field is required e.g. first name (*), if a user then tries to submit the form without populating the field or the user inputs number in place of letters, a 4xx, most times 400 (Bad Request) error indicating that the user sent the wrong information is displayed along side an error message stating the error, this helps the user know what went wrong and helps prevent them from repeating the error. Another example is when a user tries to access an incorrect resource / URL, they would get a 404 error indicating that the resource cannot be found.
Please note, as part of best practice, the front-end should do the user input/ form validation before calling the back-end.
However, using the form example above, in the case where the user inputs everything currently, but the server is down or not acting as it should, a 5xx error is thrown, most times 500 (Internal Server Error) indicating that the fault is not from the user but the server.
In summary, return a 4xx error when the fault is from the user and return a 5xx error when the fault is from the server.