Skip to content

Instantly share code, notes, and snippets.

@salahuddin-rakib
Created August 16, 2023 09:34
Show Gist options
  • Save salahuddin-rakib/464e6dea6f4de25aac44e2b7f63b654f to your computer and use it in GitHub Desktop.
Save salahuddin-rakib/464e6dea6f4de25aac44e2b7f63b654f to your computer and use it in GitHub Desktop.
Observing errors from middleware
module MyApp
class Application < Rails::Application
if Rails.env == 'test'
require 'diagnostic'
config.middleware.use(MyApp::DiagnosticMiddleware)
end
# If previous code is not working then write code this way
# if Rails.env == 'test'
# require File.expand_path('../diagnostic', __FILE__)
# config.middleware.use(MyApp::DiagnosticMiddleware)
# end
end
end
module MyApp
class DiagnosticMiddleware
FILENAME = 'diagnostic.txt'
def initialize(app)
@app = app
end
def call(env)
return @app.call(env)
rescue StandardError => e
trace = e.backtrace.select{ |l|l.start_with?(Rails.root.to_s) }.join("\n ")
msg = "\n#{e.class}\n#{e.message}\n#{trace}"
File.open(FILENAME, 'a') { |f| f.write msg }
raise e
end
end
end
# Another way to implement :
# To print in stdout:
# module MyApp
# class DiagnosticMiddleware
# def initialize(app)
# @app = app
# end
# def call(env)
# return @app.call(env)
# rescue StandardError => error
# puts error.message
# puts error.backtrace
# raise error
# end
# end
# end
# Another way to implement DiagnosticMiddleware:
# module MyApp
# class DiagnosticMiddleware
# FILENAME = File.join(Rails.root, 'log', 'test.log')
# def initialize(app)
# @app = app
# end
# def call(env)
# return @app.call(env)
# rescue StandardError => e
# trace = e.backtrace.select{ |l|l.start_with?(Rails.root.to_s) }.join("\n ")
# msg = "#{e.class}\n#{e.message}\n#{trace}\n"
# File.open(FILENAME, 'a') { |f|
# f.write "\n"
# f.write "\n"
# f.write " --- BACKTRACE --- \n"
# f.write "\n"
# f.write msg
# f.write "\n"
# f.write " --- BACKTRACE --- \n"
# f.write "\n"
# f.write "\n"
# }
# raise e
# end
# end
# end
@salahuddin-rakib
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment