What HTTP status should I return if my script throws an exception?
200 OK
or
500 Internal Server Error
Let's say user request parameters are correct but there is a bug in my script which causes an error message to appear instead of a proper response (XML, JSON or other format). What should be the HTTP status?
500 Internal Server Error is the correct status if the error can't be fixed by the client changing their request.
Use any of the 4XX statuses if the client might be able to fix their request to avoid the error (or 404 if the resource wasn't found).
200 OK is not the appropriate status in almost any error situation, because then the client thinks things are running normally (which they are not) and may continue to make the same error-causing requests.
Familiarize yourself with the available status codes in RFC2616 and find one that most appropriately fits the situation.
It depends on why the exception is thrown since they can be used for almost any error. If it's thrown because some id in the URI is not found in the database I'd say 404. On the other hand if it's because the database is down I would throw a 500. If an exception is thrown but the resulting page would still be useful to the user I would say return 200.
Review the Status Code Definitions. 500 or 400 should do for general issues, however, the more detailed you can be then the more useful the returned status will be.
Related
My team is developing a simple backend service that provides the operations ADD, GET and REMOVE a very simple item. All are triggered by an http request and they do not much besides adding, getting and removing the item from a database.
Regarding the specific scenario in which a REMOVE operation is triggered on a item that is not present in the DB (e.g. was removed before), our question is what should be the response of the service? We having been debating options like 200 + some specific message, 410 - resource gone, amongst other 2XX and 4XX possibilities, but we haven't reached a consensus.
I hope this is not Bikeshedding.
Thank you for your help.
What should be the response of the service?
It's important to highlight that status codes are meant to indicate the result of the server's attempt to understand and satisfy the client request. Having said that, 2xx status codes are unsuitable for this situation and should be avoided:
The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.
The most suitable status code would be in the 4xx range:
The 4xx (Client Error) class of status code indicates that the client seems to have erred. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
The 404 status code seems to be what you are looking for, as it indicates that the server can't find the requested resource:
6.5.4. 404 Not Found
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; [...]
If you are concerned on how the client will understand the 404 reponse, you could provide them with a payload stating that such resource is no longer available.
And just bear in mind that ADD and REMOVE are not standard HTTP methods. Hopefully that was a typo and you are using POST (or PUT) and DELETE to express operations over your resources.
What is the recommended HTTP response code for an expected server error? I know that 500 is for a server error, but it is typically for an unexpected error.
What if you wanted to throw an exception and allow the client to deal with it? Doesn't a 500 response code seem incorrect for that? What number should be used?
HTTP response codes should only reflect the status of the request itself. Something like a spam filter is endemic to the workings of your application, and has no bearing on the status of the HTTP request and response. Similar question here: How to show the internal server errors to the user?
The website posts a call to our server. We do a spam check. If it is spam, we throw an exception.
That is not an expected server error, that's a client performing an invalid request. Take a look at the 4xx range.
This is a theoretical question.
I believe I know the answer but I've received contradicting answers, so I figured I'd ask here.
On the W3C site it says:
Client Error 4xx
The 4xx class of status code is intended for cases in which the client
seems to have erred.
It also says
Server Error 5xx
Response status codes beginning with the digit "5" indicate cases in
which the server is aware that it has erred or is incapable of
performing the request.
I take this to mean that if a request is syntactically correct, but logically wrong, such as an attempt to create an object with an invalid value on a specific property, then my API should throw a 5xx Error, because the server DID understand the request, but found it to be invalid.
I have, on the other hand, been told that it should be a 4xx error (specifically 400 Bad Request) because the logical error was on the client side, as it sent an invalid value in the first place.
So, what error code SHOULD I be reporting?
5xx error will occur when the problem is on the server side. For example when you make a request with a method or protocol which is not understood by the server, when the proxy did not respond, etc. Per short: when the server was unable to fulfill the request.
In your example a 4xx error is more appropriate, because the request initiator is the source of the problem. More specific, "422 Unprocessable Entity" error is appropriate, because as RFC 4918 states:
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.
From various reasons some API designers are trying to limit themselves to a set of 3 - 5 status codes that will be used. In general this is done to ease the work for the API users, which sounds good, but sometimes this philosophy can have bigger implications.
For example, if I send a request to some API to add a new comment, I would expect a few things to be granted, like (but not limited to):
The request is POST or send me back a 405 status if not.
If the comment was added I will get back 201 response with a link to my new comment in the body.
What do I get sometimes ?
If the request method is not POST, I will get a 400 error.
If the request is POST, I will get back a 200 status and sometimes no link to my new comment.
Sounds confusing ? For me it does.
Scenario:
A POST request is sent to process an order that will result in data retrieval from an external datasource.
There are three possible results:
The datasource returned data for the request
No data was available for the request (this is viewed as an error)
The datasource couldn't be accessed (may be down for maintenance)
An obvious response for 1 is 200: OK or 201: Created (an entity is created from this request).
What status codes would be appropriate for 2 and 3?
Status codes I have considered:
503: Service Unavailable when datasource is down
500: Internal Server Error when datasource is down
502: Bad Gateway when "no data available"
404: Not Found when "no data available"
403: Forbidden when "no data available"
412: Precondition Failed when "no data available"
2) Looking back at this, I agree it should probably be either a 204 No Content or maybe a 200 with a body indicating no records or resources could be found depending on the structure returned.
404's are generally used when the resource URI doesn't exist or a resource in the URI is not found in the case of a restful service.
3) 503 Service Unavailable
The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.
Note: The existence of the 503 status code does not imply that a
server must use it when becoming overloaded. Some servers may wish
to simply refuse the connection.
3) I agree with 503 for this
2) Frankly I think a good argument could be made for using 204 in case 2 You can include metainfo in the header to indicate specifically what 'went wrong'. It really depends on how much you consider this case to be 'an error' at the API level.
If the API itself is functioning as intended, and the request was to a valid endpoint, by an authenticated and authorized user and did not cause the server to malfunction, then very few of the 400 or 500 series errors would really seem to apply.
for example, 404 usually means the URI you called does not exist, if it does exist, then using that code is misleading at least IMHO
**10.2.5 204 No Content**
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
HTTP 404 - With your own error message like "No data found".
Twitter uses 404.
Reference: https://developer.twitter.com/en/docs/basics/response-codes.html
The datasource returned data for the request
200: OK/201: CREATED
Because everything is working as expected
No data was available for the request (this is viewed as an error)
400: BAD REQUEST
The request was invalid or cannot be otherwise served. An accompanying error message will explain further inside the body.like:
HTTP 400
{
response: null,
code: "USER_101", //should be used customized error codes here
error: "User details not found"
}
The datasource couldn't be accessed (may be down for maintenance)
404: Resource/URI NOT FOUND
The URI requested or resource is invalid
Like: https://www.lipsum.com/list-page
**/list-page** is not defined/found
Find here most frequently used status codes:
200 – OK
Everything is working, The resource has been fetched and is transmitted in the message body.
201 – CREATED
A new resource has been created
204 – NO CONTENT
The resource was successfully deleted, no response body
304 – NOT MODIFIED
This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
400 – BAD REQUEST
The request was invalid or cannot be served. The exact error should be explained in the error payload.
401 – UNAUTHORIZED
The request requires user authentication.
403 – FORBIDDEN
The server understood the request but is refusing it or the access is not allowed.
404 – NOT FOUND
There is no resource behind the URI.
500 – INTERNAL SERVER ERROR API
If an error occurs in the global catch blog, the stack trace should be logged and not returned as a response.
In my opinion the best way to handle this is with a 200 no result object.
Why?
You have a response that you can do something with without a lot of trouble. I searched, everything worked correctly but there wasn't anything in the database to give a result. Therefore, result = null and a message explaining as much. If something found this in the network calls it is not a security risk.
If you are concerned with a security risk then a 204 is probably the best approach.
res.status(200).send({
result: null,
message: 'No result'
});
I've poked around a bit, but I don't see an HTTP status code for when a request's succeeds, but there is an error after the "point of no return".
e.g., Say you process a request, its committed to the database, but while returning the result you run of memory, or encounter a NPE, or what have you. It would have been a 200 response, but now, internally, you aren't able to return the proper, well-formed response.
202 Accepted doesn't seem to fit since we've already processed the request.
What status code means "Success, but errors"? Does one even exist?
HTTP doesn't have such a status code, but there is a best practice that allows you to handle such situations - redirect the user after a POST operation.
Here is a break down -
A POST request tries to modify data on the server
If the server fails, it sends a 500 error to indicate failure
If the server succeeds, it sends a 302 redirect response
The browser then sends a fresh GET request to the server
If this fails, you get a 500 error, otherwise you get a 200
So, your use case of 'Saved data but can't retrieve it immediately' translates to a 302 redirect for the initial POST, followed by a 500 for the subsequent GET.
This approach has other advantages - you get rid of the annoying 'Are you sure you want to resubmit the data?' message. Also keeps your back/forward/refresh buttons usable.
If the server is aware that it has encountered a problem, it should normally return a 5xx error. The most generic one is the 500 Server Error, which the RFC 2616 defines as follows:
500 Internal Server Error
The server encountered an unexpected condition which prevented it
from fulfilling the request.
Then it's the client's responsibility to reattempt the request. If the previous request was partially committed, it's the server's (or the database's) responsibility to roll that back, or to handle the duplicate transaction appropriately.
I agree with #Daniel that the proper response is an HTTP 500 (server error). The web application has to be written to roll back the transaction when there is an error, not leave things half-finished.
One thing you can leverage in your web application is "idempotency". This is the property of a function (or operation) that you can repeat it as many times as you like with the same result. For instance if a read fails, the client can simply retry it until it succeeds. If a deletion appears to fail, the client can again retry and the server will treat the request as valid whether or not the resource being deleted is already gone. And if an update appears to fail, the client can retry that until it gets a successful return from the server. The REST approach to architecting web services makes heavy use of idempotency to make operations robust in the face of error.