Search code examples
javaexceptionclient-serverhttp-status-code-400

How should a web server handle a http request where file POSTed by client has data in wrong format?


We have a web server which has exposed an api where the client can upload a file. That file is read in the server and certain processing happens and a http response with status code 200 is generated. Sometimes, however, a file with data in the wrong format is received by the server. How should this case be handled? By letting an exception occur, or by returning a 400 bad request?

EDIT -

Is throwing an exception equivalent to returning 500 status code? Should this be used in this case?


Solution

  • In my opinion, one shouldn't use non-200 codes to report application-level issues to client, these codes reserved purely for HTTP-level functions.

    It is sensible to just return 200 code and place application-level error code/message/whatever in HTTP response body

    However, there is at least one protocol that uses 500 codes to communicate application-level failures: SOAP. For example, here's head of HTTP response containing SOAP fault message:

    HTTP/1.1 500 Internal Server Error
    Content-Type: application/soap+xml; charset="utf-8"
    Content-Length: nnnn
    
    <?xml version='1.0' ?>
    <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
      <env:Body>
        <env:Fault>
         <env:Code>
           <env:Value>env:Sender</env:Value>
           <env:Subcode>
            <env:Value>rpc:BadArguments</env:Value>
           </env:Subcode>
         </env:Code>
    

    But, anyway, you see that not just 500 HTTP error code is returned, but application-level (SOAP) data is included with elaborate information about what happened.

    Ultimately, it's up to you to decide whether you'll use something besides 200 for your protocol. Your client requirements will decide if lone 500 error code is sufficient for them to fully communicate error and it's reasons. If it's sufficient, you don't need anything else. If it's not, invent your protocol or, better, use existing one, like SOAP or REST.