Is there a best practice for defining custom error types in a Ruby library (gem) or Ruby on Rails application? Specifically:
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
For Gems
I have seen many times that you define exceptions in this way:
gem_dir/lib/gem_name/exceptions.rb
and defined as:
module GemName
class AuthenticationError < StandardError; end
class InvalidUsername < AuthenticationError; end
end
an example of this would be something like this in httparty
For Ruby on Rails
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
and you would use it like this:
raise Exceptions::InvalidUsername