Created
August 16, 2023 09:34
-
-
Save salahuddin-rakib/464e6dea6f4de25aac44e2b7f63b654f to your computer and use it in GitHub Desktop.
Observing errors from middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got these codes from Steve Masterman public gist. The gist link: https://gist.github.com/steve9001/1443408/3917792198d7f93b129c6009fcc9292ec4b7b664