What error should be returned if response don't return expected field?

Viewed 24

Suppose you send a request to an endpoint and expect to receive a record array field as response, like this:

{
"records": [
...
],
}

Now you are processing the response.data.records, but then you find out the records array field is not present.

Should I throw an exception? If yes, what would be the best status code to describe this error?

Consider that a request was correctly formatted and sent to the endpoint.

When I receive a proper response, I'm iterating over the array and searching for a specific object. In this case, I return a 404 when the object is not found.

But here I don't even have the response.data.records array to iterate.

1 Answers

Usually when you don't expect a request to be the way that it has arrived, you could use a 400 - bad request. According to Mozilla MDN docs.

400 Bad Request - The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Because, 404 is normally used when you couldn't find a resource.

Related