Search code examples
ruby-on-railsrubyconventions

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


Is there a best practice for defining custom error types in a Ruby library (gem) or Ruby on Rails application? Specifically:

  1. Where do they belong structurally in the project? A separate file, inlined with the relevant module/class definition, somewhere else?
  2. Are there any conventions that establish when to and when not to create a new error type?

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

Solution

  • 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