ruby - 我应该如何从 HALT 不可用的类中返回 Sinatra HTTP 错误?

标签 ruby exception error-handling sinatra http-status-codes

我有一个内置于 Sinatra 中的本地应用程序的大型后端 API,它还提供一些管理网页。我正在尝试干涸代码库并将代码重构为 lib 目录中的类。

我的 API 客户端需要状态和消息,例如 200 OK 或 404 Profile Not Found。我通常会用 halt 404, 'Profile Not Found' 之类的东西来做这个。 .

halt 最简单的方法是什么?使用 HTTP 状态代码和来自类内部的消息?

旧湿码

post '/api/process_something'
  halt 403, 'missing profile_id' unless params[:profile_id].present?
  halt 404, 'offer not found' unless params[:offer_id].present?
  do_some_processing
  200
end

新干码
post '/api/process_something'
  offer_manager = OfferManager.new
  offer_manager.process_offer(params: params)
end

报价管理器.rb
class OfferManager
  def process_offer(params:)
    # halt 403, 'missing profile_id' unless params[:profile_id].present?
    # halt 404, 'offer not found' unless params[:offer_id].present?
    # halt doesn't work from in here
    do_some_processing
    200
  end
end 

最佳答案

这个问题对于 CodeReview 可能更好,但是您可以在此处的 OO 设计中看到的一种方法是“停止”路径和“快乐”路径。你的类只需要实现一些方法来帮助你在所有的 sinatra 路由和方法中保持一致。

这是一种方法,使用继承很容易在其他类中采用这种接口(interface)。

post '/api/process_something' do
  offer_manager = OfferManager.new(params)
  # error guard clause
  halt offer_manager.status, offer_manager.halt_message if offer_manager.halt?

  # validations met, continue to process
  offer_manager.process_offer
  # return back 200
  offer_manager.status
end


class OfferManager
  attr_reader :status, :params, :halt_message

  def initialize(params)
    @params = params
    validate_params
  end

  def process_offer
    do_some_processing
  end

  def halt?
    # right now we just know missing params is one error to halt on but this is where
    # you could implement more business logic if need be
    missing_params?
  end

  private

  def validate_params
    if missing_params?
      @status = 404
      @halt_message = "missing #{missing_keys.join(", ")} key(s)"
    else
      @status = 200
    end
  end

  def do_some_processing
    # go do other processing
  end

  def missing_params?
    missing_keys.size > 0
  end

  def missing_keys
    expected_keys = [:profile_id, :offer_id]
    params.select { |k, _| !expected_keys.has_key?(k) }
  end
end

关于ruby - 我应该如何从 HALT 不可用的类中返回 Sinatra HTTP 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895023/

相关文章:

ruby - 我应该在 def 中指定 &block 参数吗?

php - 队列 worker 的 Laravel 异常处理程序

java - Libgdx - 线程 "LWJGL Application"java.lang.ClassCastException 中的异常

python - 为什么某些正则表达式引擎会在单个输入字符串中匹配 .* 两次?

ruby - 如何在 Rails 中使用不同的 Webrick(不是当前 Ruby 的版本)

java - 当您的方法签名不允许抛出异常时如何抛出异常?

excel - 无法为 Excel UDF 返回正确的错误类型

php - 如果PHP脚本中断,则显示错误消息

exception-handling - Spring Integration - 在服务激活器组件中发生异常时写入错误队列

ruby - 用正则表达式替换字符串,如果某些单词与数组匹配则替换