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

后端 未结 5 2071
礼貌的吻别
礼貌的吻别 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条回答
  •  -上瘾入骨i
    2020-12-12 10:50

    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
    

提交回复
热议问题