Rails: How do I require ActiveSupport's rescue_from method? - ruby-on-rails

I have this code in application controller:
# Method to capture and handle all exceptions
rescue_from Exception do |ex|
Rails.logger.debug ex
do_stuff(ex)
end
I want to move this into a module and then:
class ApplicationController < ActionController::Base
include 'module'
...
Right now my module looks like:
# lib/exception_mailer.rb
require 'action_mailer'
require 'active_support'
module ExceptionMailer
# Method to capture and handle all exceptions
rescue_from Exception do |ex|
...
And I am getting: undefined method 'rescue_from' for ExceptionMailer:Module
I've googled 'how do i include rescue_from in a module?' -- and I'm still a little lost.

module Exceptionailer
# http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
extend ActiveSupport::Concern
included do
rescue_from Exception do |ex|
...
end
end
end

Related

Use rescue_from on model concern

I want to use rescue_from method on a model concern but neither exception error is rescued to the method i specified:
require "active_support/concern"
module CustomErrorHandler
extend ActiveSupport::Concern
include ActiveSupport::Rescuable
included do
rescue_from StandardError, with: :capture_error
end
private
def capture_error(e)
puts "Error catched!"
end
end
class FooClass
include CustomErrorHandler
def some_action
raise StandardError, 'Error'
end
end
err = FooClass.new
err.some_action
Traceback (most recent call last):
2: from (irb):28
1: from (irb):23:in `some_action'
StandardError (Error) # Didn't catch the error!
Anyone can help me on how can i solve this? Thanks!
This idea is fundamentially broken.
rescue_from is basically just syntactic sugar for:
class ThingsController < ApplicationController
around_action :wrap_in_a_rescue
def show
raise SomeKindOfException
end
private
def wrap_in_a_rescue
begin
yield
rescue SomeKindOfException
do_something_else
end
end
def do_something_else
render plain: 'Oh Noes!'
end
end
It only works because the controller declares a callback.
Its use makes sense in a controller as it rescues exceptions that occur in its callbacks as well as in the method itself and can be used with inheritiance to customize the error responses. It use does not make very much sense outside of that context.
While you could maybe fix this code by including ActiveSupport::Callbacks and declaring the requisite callbacks it is most likely a very overcomplicated solution to the original problem which can most likely be handled with a simple rescue or composition.

Best way to perform error handling using modules in Rails?

I'm pretty new to Rails and back-end API developement so excuse me if I misuse a concept or so. Right now I'm attempting to refactor a large amount of conditional error handling code that is sprinkled around the code base and move towards using an explicit list of rescued exceptions that's mixed into the API controller by including it in as a module. This will allow me to attach custom, but arbitrary, codes to each exception caught, so long as we use the bang alternatives for active record methods, and the error handling code can live in one place. So far, for the error handling module, I have something like this:
# app/lib/error/error_handling.rb
module Error
module ErrorHandling
def self.included(klass)
klass.class_eval do
rescue_from ActiveRecord::RecordNotFound do |e|
respond(:record_not_found, 404, e.to_s)
end
rescue_from ActiveRecord::ActiveRecordError do |e|
respond(e.error, 422, e.to_s)
end
rescue_from ActiveController::ParameterMissing do |e|
response(:unprocessable_entitry, 422, e.to_s)
end
rescue_from ActiveModel::ValidationError do |e|
response(e.error, 422, e.to_s)
end
rescue_from CustomApiError do |e|
respond(e.error, e.status, e.message.to_s)
end
rescue_from CanCan::AccessDenied do
respond(:forbidden, 401, "current user isn't authorized for that")
end
rescue_from StandardError do |e|
respond(:standard_error, 500, e.to_s)
end
end
end
private
def respond(_error, _status, _message)
render "layouts/api/errors", status: _status
end
end
end
Where layouts/api/errors is a view built using jbuilder.
In the ApiController we have:
# app/controllers/api/api_controller.rb
module Api
class ApiController < ApplicationController
include Error::ErrorHandling
attr_reader :active_user
layout "api/application"
before_action :authenticate_by_token!
before_action :set_uuid_header
respond_to :json
protect_from_forgery with: :null_session
skip_before_action :verify_authenticity_token, if: :json_request?
private
...
end
Unfortunately this doesn't seem to work. Running tests shows that the private methods are not being loaded at all and are considered undefined!
To be more specific, here are the errors emitted:
uninitialized constant Error::ErrorHandling::ActiveController
and
undefined local variable or method `active_user' for Api::FooController
Where active_user is an attribute that is set inside of an instance variable by a method named set_active_user. Which is obviously not being called.
However the ErrorHandling module is being evaluated. How could this be? Am I namespacing incorrectly or something?
Thanks for reading.
The answer is broken down into two parts as I believe that there are two separate problems.
unitinalized constant error
The error
uninitialized constant Error::ErrorHandling::ActiveController
can be fixed by changing this
rescue_from ActiveController::ParameterMissing do |e|
response(:unprocessable_entitry, 422, e.to_s)
end
to this:
rescue_from ::ActiveController::ParameterMissing do |e|
response(:unprocessable_entitry, 422, e.to_s)
end
(adding :: in front of the ActiveController constant)
Constant lookup in ruby takes lexical nesting into account. As you reference the Constant within
module Error
module ErrorHandling
...
end
end
ruby will try to find the constant within this namespace if the constant is undefined before. Prepending :: will tell ruby to ignore the nesting on constant lookup.
undefined local method
The error
undefined local variable or method `active_user' for Api::FooController
is raised because some code is calling the instance method active_user on the class Api::FooController where it is not defined.
I know this is an old question but I was struggling with it but found the fix. To fix the issue of:
`undefined local variable or method `active_user' for Api::FooController`
You need to include extend ActiveSupport::Concern e.g.
module Error
module ErrorHandling
extend ActiveSupport::Concern
# rest of your code
end
end

Rails rescue_from not catching exception in same file

So in my application_controller I have a helper method that raises an exception in a certain case, and a rescue_from for that exception in the same file. The structure looks something like the following:
application_controller.rb:
class ApplicationController < ActionController::Base
helper_method :my_method
def my_method
begin
# some code
rescue xyz
# some code
unless something
raise MyException.new()
end
rescue
raise MyException.new()
end
end
rescue_from 'MyException' do |e|
# some code
end
class MyException < StandardError; end
end
For some reason, when MyException is raised in my helper method, it is not caught by the rescue_from. I'm honestly not sure how to proceed...I don't think putting the rescue_from before the method would affect anything, since I have more than one handler defined like this and they work fine.

Cannot access method from included module

I'm learning ruby on rails 4, and want to use concern in ActiveSupport. Here's how I do it:
controllers/concerns/do_things_controller.rb
# file controllers/concerns/do_things_controller.rb
require 'active_support/concern'
module DoThings
extend ActiveSupport::Concern
def do_something
puts 'something'
end
included do
helper_method :do_something
end
end
controllers/application_controller.rb
# file controllers/application_controller.rb
class ApplicationController < ActionController::Base
require 'concerns/do_things_controller'
include DoThings
end
And in views/layouts/application.html.haml I call do_something, it shows error:
undefined method `do_something'
Thanks

Can I execute a method everytime I get an exception on Rails 3?

I tried almost everything on web, all I want is to call a method whenever an exception like "ActiveRecord::RecordNotFound" or "No route matches" appears.
Rescues from ApplicationController does not work, but why?
class ApplicationController < ActionController::Base
protect_from_forgery
private
def self.send_report_error(message)
Notifier.page_failure(message).deliver
end
rescue ActiveRecord::RecordNotFound
# handle not found error
send_report_error ActiveRecord::RecordNotFound.to_s
rescue ActiveRecord::ActiveRecordError
# handle other ActiveRecord errors
send_report_error ActiveRecord::ActiveRecordError.to_s
rescue # StandardError
# handle most other errors
send_report_error "common error"
rescue Exception
# handle everything else
send_report_error "common exception"
end
Use rescue_from. For example:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :send_report_error
end
http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html

Resources