Skip to content

Commit 81a8294

Browse files
committed
Fix false negative in PingController after Rails 7.2
Before Rails 7.2, ActiveRecord::Connection.connection.active? would fail if it couldn't connect to the database and succeed if it could. This was the basis for the check in the ping controller. In Rails 7.2 they now lazy connect, so until something actual uses the connection, that will return false. This creates a false negative in the PingController the very first time a connection is taken from the connection pool. Instead we can use our connectable? override method, which actually tries to make a connection before checking the connectivity. Additionally, when there was an error in the PingController, it would go through the standard error handler in the ApplicationController, which would, in turn, return a jquery-rjs payload with the error back to the client. However, this is not useful in the PingController as it's meant to be used externally. This commit introduces custom error handling to override the default handler.
1 parent affb1bc commit 81a8294

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

app/controllers/ping_controller.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
11
class PingController < ApplicationController
22
def index
3-
raise PG::Error unless ActiveRecord::Base.connection.active?
3+
raise PG::Error unless ActiveRecord::Base.connectable?
44

55
render :plain => 'pong', :status => 200
66
end
7+
8+
private def error_handler(e)
9+
message =
10+
case e
11+
when PG::Error
12+
"Unable to connect to the database"
13+
else
14+
"Unknown"
15+
end
16+
message = "ERROR: #{message} (#{e.class.name})"
17+
Rails.logger.error("#{message} - #{e.message}")
18+
render :plain => message, :status => 500
19+
end
720
end

spec/controllers/ping_controller_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,22 @@
77
expect(response.status).to eq(200)
88
expect(response.body).to eq("pong")
99
end
10+
11+
it 'fails gracefully with database errors' do
12+
expect(ActiveRecord::Base).to receive(:connectable?).and_return(false)
13+
14+
get :index
15+
16+
expect(response.status).to eq(500)
17+
expect(response.body).to eq("ERROR: Unable to connect to the database (PG::Error)")
18+
end
19+
20+
it 'fails gracefully with non-database errors' do
21+
expect(ActiveRecord::Base).to receive(:connectable?).and_raise(RuntimeError)
22+
23+
get :index
24+
25+
expect(response.status).to eq(500)
26+
expect(response.body).to eq("ERROR: Unknown (RuntimeError)")
27+
end
1028
end

0 commit comments

Comments
 (0)