我在 Rails 中有一个应用程序可以同时响应 json 和 html。
我喜欢这样,当记录在保存时返回错误时,json 答案是这样的:
{
"errors" : {
"slug" : [
"can't be blank"
],
"title" : [
"can't be blank"
]
}
}
所以我将这段代码添加到我的 ApplicationController
类中。
rescue_from ActiveRecord::RecordInvalid do |exception|
render json: { errors: exception.record.errors },
status: :unprocessable_entity
end
我希望此 rescue_from
仅在格式为 json 时被调用,否则以标准方式运行(当格式为 html 时)。我怎样才能做这样的事情?
更新 我找到了一个解决方案,但我认为它不是很好:
rescue_from ActiveRecord::RecordInvalid do |exception|
respond_to do |format|
format.json do
render json: { errors: exception.record.errors },
status: :unprocessable_entity
end
format.html { fail exception }
end
end
有没有更好的方法?
最佳答案
有更好的方法。
例如:
rescue_from ActionController::InvalidAuthenticityToken do |exception|
raise unless request.xhr?
render nothing: true, status: :unprocessable_entity
end
关于ruby-on-rails - `rescue_from` 格式为json时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939722/