gpt4 book ai didi

ruby-on-rails - Rails中的错误模式,提高 “text evaluting to RuntimeError”或提高MyModule::CustomError?

转载 作者:行者123 更新时间:2023-12-03 08:16:21 24 4
gpt4 key购买 nike

问:标题可能是太大的问题,答案可能是“取决于”?但是,提供一些实际的案例/示例应该可以帮助像我一样的开发人员识别何时应用什么。我将从我的特殊情况开始。您是否会使用自定义错误类?为什么/为什么不呢?

欢迎使用下面的其他示例,例如使用自己的错误类时。我真的很好奇。

例如:我正在使用httparty查询我们的Rails Web服务应用程序以获取一些数据。它使用基本身份验证。我将粘贴测试代码和实现。我的测试应该期望什么RuntimeError或SomeCustomError?

class MyIntegrationTest < Test::Unit::TestCase
context "connecting to someapp web service" do
should "raise not authorized if username is wrong" do
#get default MyWebserviceInterface instance, overriding username setting
ws_endpoint = build_integration_object(:username => 'wrong_username')
assert_raises RuntimeError do #TODO error design pattern?
ws_endpoint.get
end

end
end
end

实现:
class MyWebserviceInterface
include HTTParty

#Basic authentication and configurable base_uri
def initialize(u, p, uri)
@auth = {:username => u, :password => p}
@uri = uri
end

def base_uri
HTTParty.normalize_base_uri(@uri)
end

def get(path = '/somepath.xml', query_params = {})
opts = {:base_uri => base_uri, :query => query_params, :basic_auth => @auth}
response = self.class.get(path, opts)
evaluate_get_response(response)
response.parsed_response
end

def evaluate_get_response(response)
code = response.code
body = response.body
if code == 200
logger.debug "OK - CREATED code #{code}"
else
logger.error "expected code 200, got code #{code}. Response body: #{body}"
#TODO error design pattern? raise the above logged msg or a custom error?
raise SomeAppIntegration::Error(code, body)
end
end

最佳答案

在大多数情况下,我会从不从营救出或提高RuntimeError。那可能与您的代码完全无关。最好使用自定义异常。

通常,只要在库的常量中为错误命名空间,就可以随意调用错误。例如,如果有人输入了错误的用户名,则可以将YourApp::InvalidUsername作为异常对象,其定义如下:

module YourApp
class InvalidUsername < StandardError
def message
super("Yo dawg, you got your username wrong all up in here")
end
end

结束

当您 raise YourApp::InvalidUsername时,您会看到该消息出现。

关于ruby-on-rails - Rails中的错误模式,提高 “text evaluting to RuntimeError”或提高MyModule::CustomError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3787883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com