ruby-on-rails - 葡萄错误处理策略?

标签 ruby-on-rails ruby rest ruby-grape grape-entity

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

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

我很想创建一个错误处理模块并为每种类型的错误定义方法,例如...

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 类仍然非常精简。我仍然对人们可能采用的任何其他方法持开放态度。

关于ruby-on-rails - 葡萄错误处理策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528688/

相关文章:

ruby-on-rails - rails 逻辑!预购广告,如何存储信息?

ruby-on-rails - 未定义的方法 `collect' for nil :NilClass

ruby-on-rails - Metal 与 Rack 有何不同?

html - 我的 Rails 应用程序的不同应用程序布局

Java Rest 发送 double 值

android - 受信任应用程序的 Secure Rest API

ruby-on-rails - Owl Carousel Slider 不会在 Ruby on Rails 应用程序中显示

Ruby 线程不打印 kafka 消息

Ruby 对象引用与集合引用

javascript - 防止用户操纵 REST URL