Should I rely on http status codes? Or should I use some kind of special response? My server is running PHP and producing simple JSON responses.
views:
22answers:
2My client queries my server. If the response is negative (e.g. error) how should I communicate it?
I'd personally say you should do both! Return an appropriate 4xx/5xx status code to show something went wrong and include a message into your JSON response.
E.g. for a successful request:
{
"success": "true"
}
And for fail (e.g. 405 Method not allowed):
{
"success": "false",
"message": "Requested data not available"
}
It could be better if , you can go with an Entity with Two Properties as : Status & Message
.
You inherit your query result entity from the above entity.
If the operation is successful then Set the Status to True
else set Status to False
and set appropriate error message into the Message property of above entity
.
Remember that it is better you don't put exact database errors into the client side displays. That may increase the chances of hacking attacks, instead you can log the exact message on the server so that the concerned people can check the messages, if something goes wrong.
So, if Status=True
then only the client can further process the message (like accessing the properties or displaying them etc.), else if Status=False
, then the error text set at the data access logic, into the Message
property will be displayed.