I am currently writing a backend JSON API built with nodejs & express but this question can probably apply to any backend API's
What is the standard way of handling model validation errors when a bad or incomplete request is sent to the server and what response should be given to the client?
Currently, my application is sending status codes if something was to go wrong. Is this enough?
Edit: I have fully functioning validations on the client side app, so I am not overly fussed, but it would be nice to have all the angles covered.
You should perform server-side validations regardless of whether you do it client-side too.
Returning any of the 4xx, 5xx errors will do, choose the ones that describe your conditions.
It is sometimes useful in these cases to pass {wait: true}
in the options of save
or create
in order to wait for the server response before saving/adding your models.
That depends on your application and how you want to handle errors. If you want to give your users more feed back on what went wrong other than an error occured, you could create your own error object.
I send back json errors depending on what happened on the server and display any messages to the user. For example, with a login in page, if validation failed I will set the HTTP status 401 (Unauthorized) with the response text of:
{errors:
{"username": "Incorrect username and or password" }
}