Friday 30 April 2010

Webapps and HTTP Error codes

Someone recently asked me
HTTP servers can return HTTP error codes. Should an application (e.g. a grails application) send back HTTP errors/codes, or in case of error, send back an HTTP code 200, and then send back some form of application error code/message ?
IMHO you should use appropriate HTTP error codes where possible, it's just not always possible.

For example, a request for a non-existent URL really should return 404, otherwise you will find search engines repeatedly indexing you human-readable error page. Likewise, our local directory returns a real 404 if you try to look at the details for someone who dosen't exist.

I'd suggest that 'server exploded horribly' should also return 500, and that broken requests could be reported as 400, but beyond this there are few response codes that are really relevant to a web application (apart from 'functional' ones like the 300 series). By all means use anything else that makes sense, but check the standard carefully - many codes don't mean what they superficially appear to mean. How you should report an 'application' error that doesn't map on to an existing code is beyond me (200 with explanation, 400 with explination?). There are also 'errors' which are not really errors - like not finding any results in a search.

Remember that it's perfectly possible to include an application error code or message in the text of a page returned with a non-200 HTTP status code. But you do have to accept that some browsers (thank you Microsoft, but also modern Firefoxes) may suppress your useful, hand-crafted message in favour of their own generic, unhelpful one. Sometimes making your error message long enough will encourage browsers to display it after all.