Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What HTTP status code should I use for custom errors?

I need to return information about errors like: customer can't have more than 3 contacts, field Job is empty, limit of operations was exceeded.

Do I need send each error with own status code?
Can I use 400 BadRequest for all those errors?

like image 281
rnofenko Avatar asked Jan 09 '16 21:01

rnofenko


People also ask

How do I use a custom error code?

The Custom Error Code Search window displays in the work area. Choose the Create New icon. The Custom Error Code Details pop-up window displays. In the Error Code Field, enter the code value.

Can I use custom HTTP status codes?

Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. So you can return custom 4XX error codes (preferably those that are unassigned) for your own application's error conditions.

Should Put return 200 or 204?

200 OK - This is the most appropriate code for most use-cases. 204 No Content - A proper code for updates that don't return data to the client, for example when just saving a currently edited document. 202 Accepted - If the update is done asynchronous, this code can be used.

What HTTP status code typically has to deal with server errors?

HTTP Status Code 500 - Internal Server Error Instead of the problem being with pages missing or not found, this status code indicates a problem with the server. A 500 is a classic server error and will affect access to your site.


2 Answers

Can I use 400 BadRequest for all those errors?

Most certainly.

This used to be a bit questionable, because RFC 2616 defined 400 Bad Request as:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

However, there often wasn't a more applicable better status, so it was often used as the best-fit.

This has changed with RFC 7231 obsoleting RFC 2616 and giving a broader definition to 400:

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).

Because "something that is perceived to be a client error" covers a multitude of sins, it's now more explicitly applicable.

Of course, if another 4xx code does match better (e.g. 404 for a request that relates to something that doesn't exist [an ID in the message doesn't find a match]), then it is the better option.

like image 158
Jon Hanna Avatar answered Oct 23 '22 11:10

Jon Hanna


Can I use BadRequest (400) for all those errors?

Yes, that's definitely the correct status code for this kind of validation errors.

like image 21
Darin Dimitrov Avatar answered Oct 23 '22 10:10

Darin Dimitrov