原文来自于 http://travisjeffery.com/b/2012/04/rendering-errors-in-json-with-rails/
Having seen a lot of bad practices when it comes to handling and rendering errors in JSON, bad practices such as misusing HTTP statuses, success/error callbacks, and making building error messages harder than necessary, here are bad and good practices.
Here’s an example that is bad,
JavaScript,
Controller,
The biggest concern in the example above is that we’re not using HTTP statuses as they were intended which is bad both practically and semantically.
Semantically in the sense that with this implementation we have to mix error handling in a success callback. Practically since our browser and libraries can work together to extract the switch logic.
This is a good example,
JavaScript,
Controller:
注意这里的 :status => 422 方法,是使得返回的response 的状态是 422。这样ajax中就可以调用到error的回调方法。而不需要像笨办法里面的那种在success方法里面进行判断。
and return 语法是rails 中的语法,使的当前渲染后,直接退出这个方法。
With an HTTP error status (e.g. 422 unprocessable entity) our error callback is called for us, our code is more declarative and without unnecessary logic.
Another small nit-pick is that we’re now letting Rails serialize our data according to our response type, i.e. it will call to_json for us.
Another tip is to use full_messages rather than serializing the errors object as it is,
The above will present the errors in a hash where the keys are attributes and the values are errors,
full_messages on the other hand will return an array of full messages,
I once watched a Rails/Backbone screencast where the author serialized the errors object as is and spent ~30 mins manipulating the data client-side into exactly what full_messages returned.
This is much easier to work with and I have never once needed the data given by serializing model.errors.