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; endend
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; endend
and you would use it like this:
raise Exceptions::InvalidUsername
in rails you can make app/errors
directory
# app/errors/foo_error.rbclass FooError < StandardError; end
restart spring/server and it should pick it up
I think in order to have cohesive source files in your project, you should define errors in the class in which may throw them and nowhere else.
Some heirarchy can be helpful - namespaces are good at keeping redundant strings out of type names - but that's more a matter of taste - there's no need to go overboard provided you have at least one custom exception type in your app which you use throughout to differentiate between 'intentional' and 'accidental' exception cases.