葡萄error handling策略?

我正在使用Grape和Rails创建REST API。 我有基本的架构,我正在寻找“清理”的地方。 其中一个地方是error handling/处理。

我目前正在整个API的root.rb(GRAPE :: API基类)文件中解决错误。 我格式化它们然后通过rack_response发回错误。 一切正常,但是root.rb文件变得有点臃肿,所有的错误都被拯救了,其中一些有特殊的解析需要完成。 我想知道是否有人为error handling制定了一个好的策略,以便它可以移动到它自己的模块中并使root.rb(GRAPE :: API基类)相当精简。

我真的想创建一个error handling模块并为每种类型的错误定义方法,例如……

module API module ErrorHandler def record_not_found rack_response API::Utils::ApiErrors.new({type: e.class.name, message: 'Record not found'}).to_json, 404 end end end 

然后在root.rb文件中执行类似的操作

 module API class Root < Grape::API prefix 'api' format :json helpers API::ErrorHandler rescue_from ActiveRecord::RecordNotFound, with: :record_not_found # Use the helper method as the handler for this error end end 

有没有人做过这样的事情? 我一直在尝试各种风格的上述策略,但我似乎无法得到任何有用的东西。

我来到以下解决方案/策略……

我将所有错误救援移动到自己的模块,如下所示

 module API module Errors extend ActiveSupport::Concern included do rescue_from :all do |e| rack_response API::Utils::ApiErrors.new({type: e.class.name, message: e.message}).to_json, 500 end . . . end end 

然后我只是在我的基础GRAPE :: API类中包含错误

 module API class Root < Grape::API include API::Errors prefix 'api' format :json helpers API::Utils::Helpers::IndexHelpers helpers API::Utils::Helpers::WardenHelpers helpers API::Utils::Helpers::RecordHelpers . . . end end 

经过大量的实验和许多其他尝试不起作用,我认为这是一个很好的解决方案,我的基础GRAPE :: API类仍然非常精简。 我仍然对人们可能采取的任何其他方法持开放态度。