Use status code 422 for Invalidargumentexception type exceptions

Asked

Viewed 2,683 times

3

According to the PHP documentation the exception InvalidArgumentException should be used when an argument not expected by the application is received.

Second status code 400 and 422 on the website of Developer.mozila, it says:

400: The HTTP 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that was understood as a client error (for example, misshapen request syntax, invalid request message framing or misleading routing request).

422: The HTTP 422 response code Unprocessable Entity indicates that the server understands the content type of the request entity, and the request syntax is correct, but it was not possible to process the present instructions.

Which status code it would be correct to use an exception of the type InvalidArgumentException?

if (is_null($attribute)) {
    $message = sprintf('The attribute %s can not be null', $attribute);
    throw new InvalidArgumentException($message, 400);
} 


if (is_null($attribute)) {
    $message = sprintf('The attribute %s can not be null', $attribute);
    throw new InvalidArgumentException($message, 422);
} 

Or is there another status code more appropriate?

1 answer

3


The class of status code 4xx is intended for situations where the error seems to have been caused by the customer. I mean, using the status code 400 or 422 in a general way the application will be passing the understanding to the client that the error is on his side and he needs to fix it in case he performs a new communication.

Therefore, what will decide whether the correct one or the other would be to use the nomenclature adopted to develop the application. I want to explain that, both are right, and if you work with several people in one or more applications have decided to adopt as standard apply the status code 422 for exceptions of the type InvalidArgumentException the context will not change for the client. The error is still on the client’s side.

Take a look at this link. According to the author, it is recommended to use status code 422 for exceptions of the type InvalidArgumentException.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.