See 这个问题 https://stackoverflow.com/questions/574035/how-to-handle-db-constraint-violations-in-the-user-interface了解适合您情况的最佳实践。
最重要的建议(来自所述链接)是标准化处理程序查找的响应结构(成功和失败),捕获服务器层的所有异常并将它们转换为相同的结构。例如(来自这个答案 https://stackoverflow.com/questions/574035/how-to-handle-db-constraint-violations-in-the-user-interface/575092#575092):
{
success:false,
general_message:"You have reached your max number of Foos for the day",
errors: {
last_name:"This field is required",
mrn:"Either SSN or MRN must be entered",
zipcode:"996852 is not in Bernalillo county. Only Bernalillo residents are eligible"
}
}
这是 stackoverflow 使用的方法(如果你想知道其他人是如何做这种事情的);像投票这样的写操作有"Success"
and "Message"
字段,无论是否允许投票:
{ Success:true, NewScore:1, Message:"", LastVoteTypeId:3 }
As @Phil.H 指出 https://stackoverflow.com/questions/674027/what-should-a-json-service-return-on-failure-error#674046,无论你选择什么,你都应该保持一致。这说起来容易做起来难(开发中的一切都是如此!)。
例如,如果您太快地提交评论,而不是保持一致并返回
{ Success: false, Message: "Can only comment once every blah..." }
SO 将抛出服务器异常(HTTP 500
)并在他们的error
打回来。
使用 jQuery +“感觉不错”.ashx
+ HTTP [状态代码] IMO 它会给您的客户端代码库增加比其价值更多的复杂性。意识到 jQuery 不会“检测”错误代码,而是检测是否缺少成功代码。当尝试使用 jQuery 围绕 http 响应代码设计客户端时,这是一个重要的区别。你只有两个选择(是“成功”还是“错误”?),你必须自己进一步分支。如果您有少量的 Web 服务驱动少量的页面,那么可能没问题,但规模较大的情况可能会变得混乱。
这是更自然的.asmx
WebService(或 WCF)返回自定义对象而不是自定义 HTTP 状态代码。另外,您还可以免费获得 JSON 序列化。