Ruby on rails rails中的错误模式,raise";文本评估到RuntimeError“;还是引发MyModule::CustomError?
Q:标题可能太大了,答案可能是“视情况而定”?然而,提供一些实际案例/示例应该可以帮助开发人员,比如我,认识到什么时候应用什么。我将从我的特殊情况开始。您是否会使用自定义错误类?为什么 下面的例子也很受欢迎,比如当您使用自己的错误类时。我真的很想知道 Ex:我用它来查询rails web服务应用程序中的一些数据。它使用基本身份验证。我将粘贴测试代码和实现。我的测试应该期望什么,RuntimeError还是某个CustomErrorRuby on rails rails中的错误模式,raise";文本评估到RuntimeError“;还是引发MyModule::CustomError?,ruby-on-rails,ruby,design-patterns,error-handling,httparty,Ruby On Rails,Ruby,Design Patterns,Error Handling,Httparty,Q:标题可能太大了,答案可能是“视情况而定”?然而,提供一些实际案例/示例应该可以帮助开发人员,比如我,认识到什么时候应用什么。我将从我的特殊情况开始。您是否会使用自定义错误类?为什么 下面的例子也很受欢迎,比如当您使用自己的错误类时。我真的很想知道 Ex:我用它来查询rails web服务应用程序中的一些数据。它使用基本身份验证。我将粘贴测试代码和实现。我的测试应该期望什么,RuntimeError还是某个CustomError 在大多数情况下,我不会从运行时错误中营救或引发运行时错误。这可能
在大多数情况下,我不会从运行时错误中营救或引发运行时错误。这可能与您的代码完全无关。最好使用自定义异常 通常,只要在库的常量中对错误进行名称空间命名,就可以调用任何错误。例如,如果某人的用户名错误,您可以将
YourApp::InvalidUsername
作为异常对象,其定义如下:
module YourApp
class InvalidUsername < StandardError
def message
super("Yo dawg, you got your username wrong all up in here")
end
end
moduleyourapp
类InvalidUsername
结束
当您
启动应用程序::InvalidUsername
时,您将看到该消息出现。从未?根据我的经验,总是和从不很少是最好的规则。但是我同意从RuntimeError中解救是错误的,在这种情况下不应该抛出RuntimeError。@请看文档中的RuntimeError。这种类型的异常非常普遍。如果您只是在抢救任何东西,那么抢救错误的好处将大大减少。文档中的示例因尝试修改冻结数组而引发运行时错误。拯救那样的东西不是个好主意。你可以设想拯救它,因为有一个“不能失败”的代码块,但在这种情况下,我会记录异常,以便稍后修复。这是很久以前的事了。我完全同意我们不应该为运行时错误设置rescue。我仍然经常用“某物”来提升,但从来没有用过救援
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
module YourApp
class InvalidUsername < StandardError
def message
super("Yo dawg, you got your username wrong all up in here")
end
end