modular-error-handling icon indicating copy to clipboard operation
modular-error-handling copied to clipboard

rescue_from CustomError rails 5

Open 1dolinski opened this issue 6 years ago • 1 comments

Updated: Hey, thanks for your write up! In my app rescue_from is not catching NotVisibleError.

In my controller

raise Exceptions::NotVisibleError

When the error comes through into the Error handler it gets caught by the StandardError block, not CustomError.. thoughts as to why this might be?

Files, copy pasta, changed Error namespace to Exceptions

module Exceptions
  class CustomError < StandardError
    attr_reader :status, :error, :message

    def initialize(_error=nil, _status=nil, _message=nil)
      @error = _error || 422
      @status = _status || :unprocessable_entity
      @message = _message || 'Something went wrong'
    end

    def fetch_json
      Helpers::Render.json(error, message, status)
    end
  end
end
module Exceptions
  class NotVisibleError < CustomError
    def initialize
      super(:you_cant_see_me, 422, 'You can\'t see me')
    end
  end
end
module Exceptions
  module ErrorHandler
    def self.included(clazz)
      clazz.class_eval do

        rescue_from ActiveRecord::RecordNotFound do |e|
          respond(:record_not_found, 404, e.to_s)
        end
        rescue_from CustomError do |e|
          respond(e.error, e.status, e.message.to_s)
        end
        rescue_from StandardError do |e|
          respond(:standard_error, 500, e.to_s) 
        end
      end
private
    # respond_to below
end

If I byebug into it

   17: 
   18:         rescue_from StandardError do |e|
   19:           byebug
=> 20:           respond(:standard_error, 500, e.to_s) 
   21:         end
   22:       end
   23:     end
   24: 
(byebug) e
#<Exceptions::NotVisibleError: Exceptions::NotVisibleError>

1dolinski avatar Oct 30 '19 19:10 1dolinski

Apparently the last rescue_form takes priority and this is the desired behaviour... you might want to update your code as well.

https://stackoverflow.com/questions/58634123/global-error-handling-and-the-order-of-included-rescue-from

1dolinski avatar Oct 30 '19 22:10 1dolinski