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

后端 未结 5 2072
礼貌的吻别
礼貌的吻别 2020-12-12 10:10

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
5条回答
  •  失恋的感觉
    2020-12-12 11:12

    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")
    

提交回复
热议问题