Search code examples
ruby-on-railsrake

Rails : How to log all exceptions thrown in rake tasks


Using a custom ErrorLogger I've written, I am trying to find a way to log all errors happening in any of my rake tasks. One alternative would be to simply add the begin-rescue block to every single *.rake file:

# lib/tasks/example.rake
require 'error_logger/error_logger'

namespace :example do
  task generic_example: :environment do
    begin
      ...task code here
    rescue Exception => e
      ErrorLogger.log(e)
      raise e
    end
  end
end

But doing it for all task files is not very DRY, so I am wondering if there is a smarter way of doing it.

For instance, I log my controller errors putting the logging logic in the application_controller, so it runs no matter which controller is dealing with the request:

#app/controllers/application_controller.rb
require 'error_logger/error_logger'

class ApplicationController < ActionController::Base
  rescue_from Exception, with: :error_middleware

  def error_middleware(exception)
    ErrorLogger.log(exception)

    raise error
  end
end

What's the best way to do something similar in the rake tasks, writing the logging logic just once and having it applied to all rake tasks? Maybe there is some code I could add to the Rakefile to achieve it?


Solution

  • You can achieve this task, by monkey-patching rake as shown below

    module Rake
      class Task
        alias_method :invoke_without_loggable, :invoke
    
        def invoke(*args)
          begin
            invoke_without_loggable(*args)
          rescue StandardError => e
            ErrorLogger.log(e)
            raise e
          end
        end
      end
    end