Home > Software design >  Return NotFound or BadRequest from browser request
Return NotFound or BadRequest from browser request

Time:11-20

Simple question: What HTTP result do I return if my website (NOT an API call) receives an invalid request from a browser?

Suppose I have a web page that takes a URL argument, like this:

https://example.com?id=123

If the argument is invalid then I can't display the requested page. My inclination is to return a 400 Bad Request. But I have often seen code that returns a 404 Not Found.

  • If I return a 400 Bad Request then the browser will simply display a blank page and the human user will probably stare at the screen for a while until it becomes obvious that something is terminally broken.

  • If I return a 404 Not Found then the browser will immediately display some sort of error message.

The only reason that my server should ever receive a request with an invalid argument should be either a malicious (or otherwise hand-crafted) call or a coding error in my own website that creates a bogus redirect. If the call is malicious then I really don't care if the caller stares at a blank screen. And if the caller is my own incorrect redirect then the user is stuck with a broken website and it kind of doesn't matter whether the user gets a weird "not found" error or just a blank screen.

CodePudding user response:

After a conversation with another SO user (see the comments on the original post) I am led to believe that the correct answer to my question is this:

If the URL arguments are missing or invalid, return an HTTP status code as though this was an API request.

  • If a required URL argument is missing then return 400 Bad Request.

  • If a URL argument just happens to identify a resource that can't be found (for example, if the page displays the details of a widget whose ID is specified in a URL argument) then return 404 Not Found. (This, of course, is confusing since the server returns 404 Not Found if the URL specifies an endpoint that the server won't handle.)

  • If a URL argument is otherwise invalid (wrong type, out of range, etc.) then return '400 Bad Request'

  • Related