Where to define custom error types in Ruby and/or Rails?

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

Leave a Comment