David - Musings of an SRE

Custom Exception Handling

Note to self:

For some better practice, handle custom exceptions by:

  1. Declaring a custom exception module.
# In /lib/exceptions/app_exception.rb

module AppException
  class AnyExceptionName < StandardError
  end

end

Do try and keep to the relevant exception subclasses (ie. StandardError v Error). Refer to this.

# In /config/application.rb
# ensure that autoload path is un-commented to allow rails to load your custom exception library

config.autoload_paths += %W(#{config.root}/lib/exceptions)
  1. Now, you can raise AppException::AnyExceptionName anytime you want!

Edit: If you want to use AppName (as defined in config/application.rb) as the module holder for your exception, the above may not work. The above works only for newly created module.

To extend your existing Rails App module replace Step 1 with:

# In config/initializers/exceptions.rb (it can be any name you want)
class AnyExceptionName < StandardError ; end

That way, if your Rails App is named ‘AppName’, you can reference to the exception using AppName::AnyException.

**Note** libraries can only be autoloaded if they share the same camelized
filename as the module that you're trying to load.

ie. For AppException to be initialized and ready to use, the filename that is
declaring it should be app_exception.rb. Else you'll have to manually do a 'load
whateverfile.rb' even after having your config autoload path set.