2

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.

4

2 回答 2

0

无论您是否也在客户端进行验证,都应该执行服务器端验证

返回任何 4xx、5xx 错误都可以,选择描述您的情况的错误。

在这些情况下,有时在保存/添加模型之前传递或等待服务器响应{wait: true}的选项很有用。savecreate

于 2012-08-21T19:45:56.343 回答
0

这取决于您的应用程序以及您希望如何处理错误。如果你想给你的用户更多的反馈除了发生错误之外的错误,你可以创建你自己的错误对象。

我根据服务器上发生的情况发回 json 错误并向用户显示任何消息。例如,在登录页面时,如果验证失败,我将设置 HTTP 状态 401(未授权),响应文本为:

{errors: 
   {"username": "Incorrect username and or password" }
}
于 2012-08-21T20:42:02.840 回答