Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Prevent exception in cleanup masking the original exception (#68371)

metamben4f23bc973f50
diff --git a/src/metabase/app_db/connection.clj b/src/metabase/app_db/connection.clj
index fadfeb21cec..2c18214f25d 100644
--- a/src/metabase/app_db/connection.clj
+++ b/src/metabase/app_db/connection.clj
@@ -4,6 +4,7 @@
[clojure.core.async.impl.dispatch :as a.impl.dispatch]
[metabase.app-db.connection-pool-setup :as connection-pool-setup]
[metabase.app-db.env :as mdb.env]
+ [metabase.util.log :as log]
[methodical.core :as methodical]
[potemkin :as p]
[toucan2.connection :as t2.conn]
@@ -163,7 +164,11 @@
(.setAutoCommit connection false)
(thunk)
(finally
- (.setAutoCommit connection true)))
+ ;; prevent a failing .setAutoCommit call from masking the original exception
+ (try
+ (.setAutoCommit connection true)
+ (catch Throwable t
+ (log/warn t "Failed to reset the connection's autocommit flag to true")))))
(thunk))))
(comment
diff --git a/test/metabase/app_db/connection_test.clj b/test/metabase/app_db/connection_test.clj
index e7539f27595..62400e28689 100644
--- a/test/metabase/app_db/connection_test.clj
+++ b/test/metabase/app_db/connection_test.clj
@@ -155,3 +155,25 @@
(is (= "Error rolling back after previous error: Original error" (ex-message e)))
(is (= "Rollback error" (-> e ex-data :rollback-error ex-message)))
(is (= "Original error" (-> e ex-cause ex-message))))))))
+
+(deftest exception-when-resetting-autocommit-does-not-mask-original-exception-test
+ (testing "when setAutoCommit fails in finally block, the original exception is not masked"
+ (let [msg "Original transaction error"
+ autocommit-reset-called (volatile! false)
+ mock-conn (reify Connection
+ (rollback [_ _savepoint])
+ (setAutoCommit [_ value]
+ (when value
+ (vreset! autocommit-reset-called true)
+ ;; Simulate setAutoCommit(true) failing in the finally block
+ (throw (ex-info (str "setAutoCommit failed, hiding " msg) {}))))
+ (getAutoCommit [_] true)
+ (setSavepoint [_])
+ (commit [_]))]
+ (binding [t2.connection/*current-connectable* mock-conn]
+ (let [e (is (thrown? clojure.lang.ExceptionInfo
+ (t2/with-transaction [_t-conn]
+ (throw (ex-info msg {})))))]
+ ;; The original exception should be thrown, not the setAutoCommit exception
+ (is (= msg (ex-message e))))
+ (is (true? @autocommit-reset-called))))))