我正在使用Grape创建我的第一个Web服务,我对此感到困惑。当POST请求未通过AR验证时,如何响应ActiveRecord验证错误?
在我的Foo模型中,我有这个:
int main() {
Movable a=CreatenNewMovable();
return 0;
}
/* Results:
$ ./w
constructing it 1
destroying it 1
*/
Grape中的My Foo Create API如下所示:
validates :bar, {
presence: true,
uniqueness: true
}
作为一个例子,当我创建一个带有Duplicate Bar的Foo时,我会看到一个标准的Rails错误页面(使用Postman)。如何确保我的所有错误仅作为JSON对象返回?
PS。我在API类中设置了以下说明:
desc "Create a new Foo"
params do
requires :bar, type: String, allow_blank: false
end
post do
::Foo.create!({
bar: params[:bar]
})
end
答案 0 :(得分:2)
您可以在API模块中使用带有参数rescue_from
的方法ActiveRecord::RecordInvalid
,我认为这是实现您打算做的更优雅的方式。将块传递给该方法将允许您获取错误消息并进一步处理它。这样您就可以统一处理所有验证错误。
例如:
rescue_from ActiveRecord::RecordInvalid do |error|
message = error.record.errors.messages.map { |attr, msg| msg.first }
error!(message.join(", "), 404)
end
答案 1 :(得分:0)
这是一个简单的例子:
get "" do
begin
present Region.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
not_found_error(e)
end
end
所以我创建了简单的帮手:
module YourApi::V1::ErrorsHelper
def not_found_error(e)
error!({ error: { message: "#{e.message}", error: "#{e.class} error", code: 404 }}, 404)
end
end
因此,只需使用方法error!
并使用您想要的方式处理消息,类型和代码。