在Ruby和/或Rails中的哪里定义自定义错误类型? [英] Where to define custom error types in Ruby and/or Rails?
问题描述
是否存在在Ruby库(gem)或Ruby on Rails应用程序中定义自定义错误类型的最佳实践?具体来说:
Is there a best practice for defining custom error types in a Ruby library (gem) or Ruby on Rails application? Specifically:
- 它们在项目中在结构上属于哪儿?
- 是否有任何约定确立何时 to 和何时 not 创建新的错误类型?
- Where do they belong structurally in the project? A separate file, inlined with the relevant module/class definition, somewhere else?
- Are there any conventions that establish when to and when not to create a new error type?
不同的库有不同的处理方式,我还没有注意到任何实际的模式。有些库始终使用自定义错误类型,而另一些则根本不使用它们。一些具有扩展StandardError的所有错误,而另一些具有嵌套的层次结构;
Different libraries have different ways of doing things, and I haven't noticed any real patterns. Some libraries always use custom error types while others don't use them at all; some have all errors extending StandardError while others have nested hierarchies; some are just empty class definitions, others have all sorts of clever tricks.
哦,只是因为我觉得调用这些错误类型有点模棱两可,所以我的意思是:
Oh, and just because I feel like calling these "error types" is sort of ambiguous, what I mean is this:
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
推荐答案
宝石
我已经多次看到您以这种方式定义异常:
I have seen many times that you define exceptions in this way:
gem_dir /lib/gem_name/exceptions.rb
gem_dir/lib/gem_name/exceptions.rb
并定义为:
module GemName
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
end
例如,< a href = https://github.com/jnunemaker/httparty/blob/master/lib/httparty/exceptions.rb> httparty
对于Ruby on Rails
将它们放在lib /文件夹下的名为exceptions.rb的文件中,该文件如下所示:
Put them in your lib/ folder under a file called exceptions.rb, which would look something like this:
module Exceptions
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
end
,您将像这样使用它:
raise Exceptions::InvalidUsername
这篇关于在Ruby和/或Rails中的哪里定义自定义错误类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!