views:

22

answers:

2

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.

+1  A: 

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"
}
halfdan
Thank you, but than I have another question. I don't know HTTP very well. How the server decides wether to show the default 404 page or my error message?
gurghet
In case of 404 the server wouldn't execute your script (unless you did some sort of rewriting) so the default 404 error page would be shown. Otherwise the server _should_ use the code + body your script returned.
halfdan
You have to decide the HTTP code using php header function for example <?php header("HTTP/1.0 404 Not Found"); ?>
Luca Bernardi
sì quello l'ho fatto ma dopo la pagina mi appare normalmente, almeno da browser.
gurghet
+1  A: 

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.

Siva Gopal