Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you define a custom exception type?

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

What is custom error handling?

Suggest Edits. You can provide your own custom error handler logic to standardize across your production environment. This error handler is called when an unknown feature key is referenced. Here is a code example where an error handler from the SDK is used.

Can you throw custom exception with error object?

While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object.


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

in rails you can make app/errors directory

# app/errors/foo_error.rb
class 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.


This is an old question, but I wanted to share how I'm handling custom errors in Rails, including attaching error messages, testing, and how to handle this with ActiveRecord models.

Creating Custom Error

class MyClass
  # create a custome error
  class MissingRequirement < StandardError; end

  def my_instance_method
    raise MyClass::MissingRequirement, "My error msg" unless true   
  end
end

Testing (minitest)

test "should raise MissingRequirement if ____ is missing"
  # should raise an error
  error = assert_raises(MyClass::MissingRequirement) {
    MyClass.new.my_instance_method
  }

  assert error.message = "My error msg"
end

With ActiveRecord

I think it's worth noting that if working with an ActiveRecord model, a popular pattern is to add an error to the model as described below, so that your validations will fail:

def MyModel < ActiveRecord::Base
  validate :code_does_not_contain_hyphens

  def code_does_not_contain_hyphens
    errors.add(:code, "cannot contain hyphens") if code.include?("-")
  end
end

When validations are run, this method will piggy-back onto ActiveRecord's ActiveRecord::RecordInvalid error class and will cause validations to fail.

Hope this helps!


To ensure that autoloading works as expected in Rails 4.1.10 for multiple custom error classes, you'll want to specify separate files for each. This should work in development with its dynamically reloading.

This is how I setup errors in a recent project:

In lib/app_name/error/base.rb

module AppName
    module Error
        class Base < StandardError; end
    end
end

and in subsequent custom errors, like in lib/app_name/error/bad_stuff.rb

module AppName
    module Error
        class BadStuff < ::AppName::Error::Base; end
    end
end

You should then be able to call your errors via:

 raise AppName::Error::BadStuff.new("Bad stuff just happened")