Tag: 葡萄实体

葡萄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 […]