Skip to content

rescue_from CustomError rails 5 #1

Open
@1dolinski

Description

@1dolinski

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>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions