我应该如何从HALT不可用的类内部返回Sinatra HTTP错误?

贾斯汀·席尔(Justin Schier)

我有一个大型的后端API,用于在Sinatra中构建的本机应用程序,该API还可以提供一些管理网页。我正在尝试清理代码库,并将代码重构为lib目录中的类。

我的API客户端需要状态和消息,例如200 OK或404未找到配置文件。我通常会用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

offer_manager.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路由和方法之间保持一致。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我该如何返回记录不可用的错误消息?

http.Get返回协议不可用错误

如何修复HTTP错误503:服务不可用错误

HTTP错误:503服务不可用IntelliJ IDEA GWT

码头:HTTP错误:503 /服务不可用

IIS 8-HTTP错误503。服务不可用

如何测试服务不可用性和抛出的HTTP错误

我的控制器不断返回错误“请求的资源不可用”

<servicename>在angular2的错误函数内部不可用

Http Get返回错误

(a)Smack在login()上返回“服务不可用(503)”错误

我收到“请求的资源不可用” 404错误

错误网页不可用

如何解决spring bean不可用的错误?

如何诊断“资源不可用”错误Apache Tomcat?

urllib.error.HTTPError:HTTP错误503:服务不可用python

http错误503服务不可用。应用程序池在访问网站时停止

HTTP 错误 503:尝试下载 MNIST 数据时服务不可用

Spring MVC中的重定向错误(http状态404请求的资源不可用jsp)

HTTPError:HTTP错误503:服务不可用的goslate语言检测请求:Python

JBoss错误报告:HTTP状态404-Servlet不可用

如果用户尝试执行对其不可用的操作,什么是适当的HTTP错误代码

Windows 10秋季更新后,HTTP错误503服务在IIS上不可用

HTTP错误:503原因:由码头提供的服务不可用

在HTTP HOST标头中包含端口号会导致服务不可用错误

Geopy 返回 HTTP 错误 400:错误请求

数据流错误-“ 500内部服务器错误”和“ 503服务不可用”

如何修复 HTTP 错误 400:错误请求?

如果资源不可用于请求的操作,HTTP状态代码应该是什么?