Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rescue_from CustomError rails 5 #1

Open
1dolinski opened this issue Oct 30, 2019 · 1 comment
Open

rescue_from CustomError rails 5 #1

1dolinski opened this issue Oct 30, 2019 · 1 comment

Comments

@1dolinski
Copy link

1dolinski commented Oct 30, 2019

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant