Skip to content

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

Track ex-info API data better (#83774)

Nathan Voxland259a871aa822
diff --git a/.cljfmt.edn b/.cljfmt.edn
index 5c845c7d45e..6818dbf6393 100644
--- a/.cljfmt.edn
+++ b/.cljfmt.edn
@@ -334,6 +334,7 @@
metabase.upload.impl-test/with-upload-table! [[:inner 0]]
metabase.upload.types/with-currency [[:default]]
metabase.upload.types/with-parens [[:default]]
+ metabase.util.api-error/exposing [[:block 1]]
metabase.util.async/cancelable-thread [[:block 0]]
metabase.util.date-2/with-time-zone-same-instant [[:default]]
metabase.util.encryption-test/with-secret-key [[:block 1]]
diff --git a/enterprise/backend/src/metabase_enterprise/gsheets/api.clj b/enterprise/backend/src/metabase_enterprise/gsheets/api.clj
index d24cb0307ee..576a7b71525 100644
--- a/enterprise/backend/src/metabase_enterprise/gsheets/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/gsheets/api.clj
@@ -93,7 +93,9 @@
:status-code status-code
:hm/response (loggable-response hm-response)
:message message
- :error_message ((comp :status-reason :body) hm-response)})))))
+ :error_message ((comp :status-reason :body) hm-response)
+ ;; Harbormaster's status and body, to help debug a failed request
+ :response/keys #{:hm/response}})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MB <-> HM APIs
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
index 27998f46fc7..b43320023d1 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
@@ -38,7 +38,8 @@
current)
{:status-code 409
:branch_mismatch true
- :current_branch current})))
+ :current_branch current
+ :response/keys #{:branch_mismatch :current_branch}})))
requested-branch))
(api.macros/defendpoint :post "/import" :- remote-sync.schema/ImportResponse
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
index ae53b4ba66c..8ea85a507cf 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
@@ -1651,7 +1651,8 @@
:conflicts true
;; The un-pushed local changes a switch would discard, so the client can name exactly
;; what would be lost without a second round-trip to /dirty.
- :dirty_objects (remote-sync.object/dirty-objects)})))
+ :dirty_objects (remote-sync.object/dirty-objects)
+ :response/keys #{:conflicts :dirty_objects}})))
(run-async! "import" branch
(fn [task-id]
(when (branch-changed-since-scheduling? pre-task-branch)
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
index 218e9dc18b4..7da5ba2d14c 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
@@ -72,12 +72,13 @@
(when-not (isa? col-base-type table-col-base-type)
(let [msg (tru "Sandbox Questions can''t return columns that have different types than the Table they are sandboxing.")]
(throw (ex-info msg
- {:type qp.error-type/bad-configuration
- :status-code 400
- :message msg
- :new-col col
- :expected table-col-base-type
- :actual (:base_type col)})))))))
+ {:type qp.error-type/bad-configuration
+ :status-code 400
+ :message msg
+ :new-col col
+ :expected table-col-base-type
+ :actual (:base_type col)
+ :response/keys #{:expected :actual}})))))))
(defn- merge-sandbox-into-graph
"Merges a single sandboxing policy into the permissions graph. Adjusts permissions at the database or schema level,
diff --git a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
index a81c60b6c79..a55d55436de 100644
--- a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
@@ -115,10 +115,11 @@
(defn- throw-scim-error
[status message]
(throw (ex-info message
- {:schemas [error-schema-uri]
- :detail message
- :status status
- :status-code status})))
+ {:schemas [error-schema-uri]
+ :detail message
+ :status status
+ :status-code status
+ :response/keys #{:schemas :detail :status}})))
(defn- scim-response
"Wraps an object in a response with the correct SCIM content-type. Status defaults to 200 unless otherwise specified."
@@ -301,10 +302,11 @@
(catch Exception e
(let [message (format "Error updating user: %s" (ex-message e))]
(throw (ex-info message
- {:schemas [error-schema-uri]
- :detail message
- :status 400
- :status-code 400})))))))))
+ {:schemas [error-schema-uri]
+ :detail message
+ :status 400
+ :status-code 400
+ :response/keys #{:schemas :detail :status}})))))))))
(defn- patch->boolean
"SCIM sends `active` as a JSON boolean, but clients in the wild send the strings \"true\"/\"false\" too. Anything
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/api.clj b/enterprise/backend/src/metabase_enterprise/security_center/api.clj
index 186ec778468..b3702d540d9 100644
--- a/enterprise/backend/src/metabase_enterprise/security_center/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/security_center/api.clj
@@ -143,7 +143,9 @@
(fn [request respond raise]
(when-not (premium-features/security-center-enabled?)
(throw (ex-info (tru "Security Center is not available on this instance.")
- {:status-code 402 :status "error-premium-feature-not-available"})))
+ {:status-code 402
+ :status "error-premium-feature-not-available"
+ :response/keys #{:status}})))
(handler request respond raise)))))
(def ^{:arglists '([request respond raise])} routes
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
index ef21d94edfe..9d68b46d1f4 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
@@ -65,8 +65,9 @@
(defn- throw-not-configured-error []
(throw
(ex-info (tru "SSO has not been enabled and/or configured")
- {:status-code 400
- :status "error-sso-disabled"})))
+ {:status-code 400
+ :status "error-sso-disabled"
+ :response/keys #{:status}})))
(defmethod sso-get :default
[_]
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
index f8e84eeb490..64ca4453e40 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
@@ -45,15 +45,17 @@
[]
(throw
(ex-info (tru "Embedding SDK for React is disabled. Enable it in the embedding settings.")
- {:status "error-embedding-sdk-disabled"
- :status-code 402})))
+ {:status "error-embedding-sdk-disabled"
+ :status-code 402
+ :response/keys #{:status}})))
(defn- throw-simple-embedding-disabled
[]
(throw
(ex-info (tru "You need to turn on modular embedding in the embedding settings.")
- {:status "error-embedding-simple-disabled"
- :status-code 402})))
+ {:status "error-embedding-simple-disabled"
+ :status-code 402
+ :response/keys #{:status}})))
(defn ^:private generate-response-token
[session jwt-data]
diff --git a/enterprise/backend/src/metabase_enterprise/transform_testing/validator.clj b/enterprise/backend/src/metabase_enterprise/transform_testing/validator.clj
index 73110d6c54b..bfae0b212fb 100644
--- a/enterprise/backend/src/metabase_enterprise/transform_testing/validator.clj
+++ b/enterprise/backend/src/metabase_enterprise/transform_testing/validator.clj
@@ -190,19 +190,22 @@
::transform-testing.errors/missing-inputs
(tru "The transform reads table(s) with no declared test input: {0}. Add an input for each."
(str/join ", " (map table-label missing)))
- {:tables (mapv table-label missing)})))
+ {:tables (mapv table-label missing)
+ :response/keys #{:tables}})))
(when-let [unused (seq (unused-inputs inputs referenced-tables default-schema))]
(throw (transform-testing.errors/ex
::transform-testing.errors/unused-inputs
(tru "Test input(s) declared for table(s) the transform does not read: {0}. Remove them."
(str/join ", " (map table-label unused)))
- {:tables (mapv table-label unused)})))
+ {:tables (mapv table-label unused)
+ :response/keys #{:tables}})))
(when-let [colliding (seq (colliding-inputs inputs default-schema))]
(throw (transform-testing.errors/ex
::transform-testing.errors/duplicate-input-table
(tru "Duplicate test inputs; each input table may be declared only once: {0}"
(str/join ", " colliding))
- {:tables (vec colliding)})))
+ {:tables (vec colliding)
+ :response/keys #{:tables}})))
(let [temp-tables (into #{} (map :table) (vals replacements))]
(check-rewrite driver rewritten-transform temp-tables nil)
(doseq [{:keys [name sql]} expectations
diff --git a/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj b/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
index cec14d0622a..bf4947e0922 100644
--- a/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
@@ -564,12 +564,10 @@
{:primary-key [:id]}]]
(mt/with-temp-vals-in-db :model/Database (mt/id) {:settings {:database-enable-table-editing false}}
(testing "execute-form should return 400 error when data editing is not enabled"
- (is (= {:message "Data editing is not enabled."}
- (select-keys
- (mt/user-http-request :crowberto :post 400 execute-form-url
- {:scope {:table-id table-id}
- :action "data-grid.row/create"})
- [:message])))))))
+ (is (= "Data editing is not enabled."
+ (mt/user-http-request :crowberto :post 400 execute-form-url
+ {:scope {:table-id table-id}
+ :action "data-grid.row/create"})))))))
(testing "Non auto-incrementing pk"
(action-v2.tu/with-test-tables! [table-id [(ordered-map
:id [:int]
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/card_api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/card_api_test.clj
index c69aeddde98..74be138a6fb 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/card_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/card_api_test.clj
@@ -24,7 +24,8 @@
(let [response (mt/user-http-request :crowberto :post 400 "card/collections"
{:collection_id synced-id
:card_ids [root-card-id]})]
- (is (= "Uses content that is not remote synced." (:message response))))
+ (is (= "Uses content that is not remote synced." (:message response)))
+ (is (seq (:non-remote-synced-models response))))
(testing "card is not moved - transaction rolled back"
(is (nil? (t2/select-one-fn :collection_id :model/Card root-card-id)))))))
@@ -41,7 +42,8 @@
(let [response (mt/user-http-request :crowberto :post 400 "card/collections"
{:collection_id regular-id
:card_ids [source-card-id]})]
- (is (= "Used by remote synced content." (:message response))))
+ (is (= "Used by remote synced content." (:message response)))
+ (is (seq (:remote-synced-models response))))
(testing "card is not moved - transaction rolled back"
(is (= synced-id (t2/select-one-fn :collection_id :model/Card source-card-id)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/collection_api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/collection_api_test.clj
index 97810b2434a..05fad75f132 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/collection_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/collection_api_test.clj
@@ -1,7 +1,6 @@
(ns ^:synchronized metabase-enterprise.remote-sync.collection-api-test
{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase-enterprise.remote-sync.collection-api-test]}}}}}}
(:require
- [clojure.string :as str]
[clojure.test :refer :all]
[diehard.core :as dh]
[metabase-enterprise.remote-sync.settings :as settings]
@@ -68,7 +67,8 @@
:dataset_query (mt/mbql-query nil {:source-table (str "card__" up-card-id)})}]
(let [response (mt/user-http-request :crowberto :put 400 (str "collection/" (:id regular-collection))
{:parent_id (:id remote-parent)})]
- (is (str/includes? (str response) "remote-synced"))
+ (is (= "Uses content that is not remote synced." (:message response)))
+ (is (seq (:non-remote-synced-models response)))
(is (nil? (t2/select-one-fn :parent_id :model/Collection :id (:id regular-collection))))
(is (false? (t2/select-one-fn :is_remote_synced :model/Collection :id (:id regular-collection)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/dashboard_api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/dashboard_api_test.clj
index 6aba73e8067..06515ea17d6 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/dashboard_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/dashboard_api_test.clj
@@ -53,7 +53,8 @@
{:collection_id target-id})]
;; Verify error response contains dependency information
(is (str/includes? (:message response) "content that is not remote synced")
- "Error message should mention content that is not remote synced"))
+ "Error message should mention content that is not remote synced")
+ (is (seq (:non-remote-synced-models response))))
;; Verify the transaction was rolled back - dashboard should not be moved
(let [unchanged-dash (t2/select-one :model/Dashboard :id dash-id)]
(is (= source-id (:collection_id unchanged-dash))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
index 5a691beae4c..033fa19fbe2 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/explorations_test.clj
@@ -232,7 +232,7 @@
{:creator-id (mt/user->id :rasta) :data-access-token token}
(fn [{:keys [query]}]
(testing "lucky is a non-admin with full data access and no sandbox"
- (is (=? {:message #"Cannot show cached results: your data access differs.*"}
+ (is (=? #"Cannot show cached results: your data access differs.*"
(mt/user-http-request :lucky :get 403 (format "exploration/query/%d" (:id query))))
"the denial is the lens refusing, not a missing data perm"))
(testing "while a superuser streams it (bypass)"
@@ -425,7 +425,7 @@
:model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)
:group_id (:id escape-group)}]
(perms/set-database-permission! escape-group (mt/id) :perms/view-data :unrestricted)
- (is (=? {:message #"Cannot show cached results: your data access differs.*"}
+ (is (=? #"Cannot show cached results: your data access differs.*"
(mt/user-http-request :rasta :get 403 (format "exploration/query/%d" (:id query))))
"the denial is the lens refusing, not a missing data perm")))
(testing "a superuser streams the cached result (bypass — superusers see every exploration)"
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
index 8814f91245a..f7d955ad499 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
@@ -393,8 +393,8 @@
(count (mt/rows (mt/user-http-request :rasta :post 202 "dataset" (mt/mbql-query venues)))))]
(is (= 1 (sandboxed-row-count)))
(is (= "You do not have permissions to modify a snippet that is used for row and column level security."
- (:message (mt/user-http-request editor :put 403 (str "native-query-snippet/" (:id snippet))
- {:content "1 = 1"}))))
+ (mt/user-http-request editor :put 403 (str "native-query-snippet/" (:id snippet))
+ {:content "1 = 1"})))
(is (= "ID = 1" (t2/select-one-fn :content :model/NativeQuerySnippet :id (:id snippet))))
(is (= 1 (sandboxed-row-count)))))))))
@@ -424,8 +424,8 @@
latitude (api-venues-col "LATITUDE")]
(is (= ["ID" "NAME" "CATEGORY_ID"] (sandboxed-venues-field-names)))
(is (= "You do not have permissions to modify a question that is used for row and column level security."
- (:message (mt/user-http-request :rasta :put 403 (str "card/" card-id)
- {:result_metadata (conj (vec original) latitude)}))))
+ (mt/user-http-request :rasta :put 403 (str "card/" card-id)
+ {:result_metadata (conj (vec original) latitude)})))
(is (= original (t2/select-one-fn :result_metadata :model/Card :id card-id)))
(is (= ["ID" "NAME" "CATEGORY_ID"] (sandboxed-venues-field-names))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
index 8b125b1e9b0..e0225e81436 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
@@ -184,17 +184,17 @@
res (mt/user-http-request :crowberto :post 400 "ee/serialization/export" {}
:collection fake-eid :data_model false :settings false)]
(is (re-find #"Could not find Collection with entity ID"
- (str (:message res))))
+ (str res)))
(is (re-find #"abcdefghijklmnopqrstu"
- (str (:message res))))))
+ (str res)))))
(testing "Nonexistent collection ID names the collection the user asked for"
(let [missing-id Integer/MAX_VALUE
res (mt/user-http-request :crowberto :post 400 "ee/serialization/export" {}
:collection missing-id :data_model false :settings false)]
(is (re-find #"Could not find Collection with ID"
- (str (:message res))))
+ (str res)))
(is (re-find (re-pattern (str missing-id))
- (str (:message res))))))))
+ (str res)))))))
(testing "We've left no new files, every request is cleaned up"
;; if this breaks, check if you consumed every response with io/input-stream
(is (= known-files
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
index 33e02ee879c..0fb5cac45d7 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
@@ -351,19 +351,17 @@
"https:///badsite.com"]]
(is
(= "Invalid redirect URL"
- (->
- (client/client
- :get 400 "/auth/sso" {:request-options {:redirect-strategy :none}}
- :return_to redirect-uri
- :jwt
- (jwt/sign
- {:email "[email protected]"
- :first_name "Rasta"
- :last_name "Toucan"
- :extra "keypairs"
- :are "also present"}
- default-jwt-secret))
- :message)))))))
+ (client/client
+ :get 400 "/auth/sso" {:request-options {:redirect-strategy :none}}
+ :return_to redirect-uri
+ :jwt
+ (jwt/sign
+ {:email "[email protected]"
+ :first_name "Rasta"
+ :last_name "Toucan"
+ :extra "keypairs"
+ :are "also present"}
+ default-jwt-secret))))))))
(deftest expired-jwt-test
(testing "Check an expired JWT"
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
index f3b38e678f4..01168f20886 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
@@ -534,7 +534,7 @@
{:request-options {:redirect-strategy :none}}
:redirect redirect-url)]
(testing (format "\n%s should not redirect" redirect-url)
- (is (= "Invalid redirect URL" (:message get-response)))))))))))))
+ (is (= "Invalid redirect URL" get-response))))))))))))
(deftest login-create-account-test
(testing "A new account will be created for a SAML user we haven't seen before"
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
index 13dae31026a..a8c1804a502 100644
--- a/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
@@ -73,7 +73,7 @@
:is_tenant_group false}]
(mt/with-model-cleanup [:model/User]
(testing "tenant users cannot be added to non-tenant groups via POST"
- (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}
+ (is (=? "Cannot add non-tenant user to tenant-group or vice versa"
(mt/user-http-request :crowberto :post 400 "user"
{:first_name "External"
:last_name "User"
@@ -82,7 +82,7 @@
:user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}
{:id normal-group-id}]}))))
(testing "internal users cannot be added to tenant groups via POST"
- (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}
+ (is (=? "Cannot add non-tenant user to tenant-group or vice versa"
(mt/user-http-request :crowberto :post 400 "user"
{:first_name "Internal"
:last_name "User"
@@ -101,13 +101,13 @@
:is_tenant_group false}]
(testing "tenant users cannot be added to non-tenant groups via PUT"
(mt/with-temp [:model/User {external-user-id :id} {:tenant_id tenant-id}]
- (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}
+ (is (=? "Cannot add non-tenant user to tenant-group or vice versa"
(mt/user-http-request :crowberto :put 400 (str "user/" external-user-id)
{:user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}
{:id normal-group-id}]})))))
(testing "internal users cannot be added to tenant groups via PUT"
(mt/with-temp [:model/User {internal-user-id :id} {}]
- (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}
+ (is (=? "Cannot add non-tenant user to tenant-group or vice versa"
(mt/user-http-request :crowberto :put 400 (str "user/" internal-user-id)
{:user_group_memberships [{:id (u/the-id (perms/all-users-group))}
{:id tenant-group-id}]}))))))))))
@@ -121,7 +121,7 @@
:is_tenant_group true}]
(testing "cannot create tenant user as group manager via POST"
(mt/with-model-cleanup [:model/User]
- (is (=? {:message "Tenant users cannot be made group managers"}
+ (is (=? "Tenant users cannot be made group managers"
(mt/user-http-request :crowberto :post 400 "user"
{:first_name "External"
:last_name "Manager"
@@ -133,7 +133,7 @@
(testing "cannot make external user group manager via PUT"
(mt/with-temp [:model/User {external-user-id :id} {:tenant_id tenant-id}]
;; This test is expected to fail until group manager restrictions are implemented
- (is (=? {:message "Tenant users cannot be made group managers"}
+ (is (=? "Tenant users cannot be made group managers"
(mt/user-http-request :crowberto :put 400 (str "user/" external-user-id)
{:user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}
{:id tenant-group-id
diff --git a/enterprise/backend/test/metabase_enterprise/transforms_inspector/api_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_inspector/api_test.clj
index d2460f66d3e..d236b9c2d09 100644
--- a/enterprise/backend/test/metabase_enterprise/transforms_inspector/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/transforms_inspector/api_test.clj
@@ -18,8 +18,8 @@
(mt/with-data-analyst-role! (mt/user->id :lucky)
(mt/with-db-perm-for-group! (perms-group/all-users) (mt/id) :perms/transforms :yes
(is (= "Lens data not available"
- (:message (mt/user-http-request :lucky :get 404
- (format "ee/transforms/%d/inspect/no-such-lens" transform-id)))))))))))
+ (mt/user-http-request :lucky :get 404
+ (format "ee/transforms/%d/inspect/no-such-lens" transform-id))))))))))
;;; -------------------------------------------------- Inspector Query API --------------------------------------------------
diff --git a/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
index 599216046ef..6981c206f96 100644
--- a/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/transforms_python/api_test.clj
@@ -33,7 +33,7 @@
(mt/user-http-request :lucky :get 200 "ee/transforms-python/library/common"))))
(testing "rejects invalid paths"
(is (= "Invalid library path. Only 'common' is currently supported."
- (:message (mt/user-http-request :lucky :get 400 "ee/transforms-python/library/invalid-path"))))))))))
+ (mt/user-http-request :lucky :get 400 "ee/transforms-python/library/invalid-path")))))))))
(deftest put-library-path-test
(testing "PUT /api/ee/transforms-python/library/:path"
@@ -85,8 +85,8 @@
(is (= 1 (t2/count :model/PythonLibrary)) "Should not create duplicate records"))
(testing "rejects invalid paths"
(is (= "Invalid library path. Only 'common' is currently supported."
- (:message (mt/user-http-request :lucky :put 400 "ee/transforms-python/library/invalid-path"
- {:source "def test(): pass"}))))))))))
+ (mt/user-http-request :lucky :put 400 "ee/transforms-python/library/invalid-path"
+ {:source "def test(): pass"})))))))))
(deftest test-run-test
(mt/with-premium-features #{:transforms-basic :transforms-python}
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
index c2f9719e6a6..735c83cd404 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
@@ -2,6 +2,7 @@ import { type FormEvent, useState } from "react";
import { c, t } from "ttag";
import { skipToken, useGetUserQuery } from "metabase/api";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { CopyButton } from "metabase/common/components/CopyButton";
import { ExternalLink } from "metabase/common/components/ExternalLink";
import { Markdown } from "metabase/common/components/Markdown";
@@ -126,7 +127,7 @@ function GoogleSheetsConnectModal({
onClose(true);
})
.catch((response) => {
- setErrorMessage(response?.data?.message ?? "Something went wrong");
+ setErrorMessage(getErrorMessage(response));
});
};
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
index 36f8afc4da8..40846503414 100644
--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
@@ -11,6 +11,7 @@ import {
useGetTableQuery,
useValidateGroupTableAccessPolicyMutation,
} from "metabase/api";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { ActionButton } from "metabase/common/components/ActionButton";
import {
QuestionPickerModal,
@@ -55,8 +56,6 @@ import {
import S from "./EditSandboxingModal.module.css";
-const getErrorMessage = () => t`An error occurred.`;
-
const getNormalizedPolicy = (
policy: GroupTableAccessPolicy | GroupTableAccessPolicyDraft,
shouldUseSavedQuestion: boolean,
@@ -339,10 +338,7 @@ const EditSandboxingModal = ({
</div>
{error && (
<div className={cx(CS.flex, CS.alignCenter, CS.my2, CS.textError)}>
- {typeof error === "string"
- ? error
- : // @ts-expect-error provide correct type for error
- (error.data.message ?? getErrorMessage())}
+ {getErrorMessage(error, t`An error occurred.`)}
</div>
)}
</div>
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/admin/AdminDatabaseTableEditingSection.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/admin/AdminDatabaseTableEditingSection.tsx
index 88b0d15f170..376d727e99e 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/admin/AdminDatabaseTableEditingSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/admin/AdminDatabaseTableEditingSection.tsx
@@ -7,10 +7,10 @@ import {
Label,
} from "metabase/admin/databases/components/DatabaseFeatureComponents";
import { DatabaseInfoSection } from "metabase/admin/databases/components/DatabaseInfoSection";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { hasDbRoutingEnabled } from "metabase/common/utils/database";
import { ALLOWED_ENGINES_FOR_TABLE_EDITING } from "metabase/databases/constants";
import { Alert, Box, Flex, Icon, Switch } from "metabase/ui";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import type {
Database,
DatabaseData,
@@ -146,5 +146,5 @@ function getResponseErrorMessageReason(error: unknown): string | undefined {
return error.data.reasons[0]?.message ?? undefined;
}
- return getResponseErrorMessage(error);
+ return findErrorMessage(error);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/toasts/getUpdateErrorMessage.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/toasts/getUpdateErrorMessage.tsx
index 8de7f614043..5b787ca86c3 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/toasts/getUpdateErrorMessage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/toasts/getUpdateErrorMessage.tsx
@@ -1,5 +1,6 @@
import { t } from "ttag";
+import { getErrorMessage } from "metabase/api/utils/errors";
import type { GenericErrorResponse } from "metabase/utils/errors";
export const getUpdateApiErrorMessage = (
@@ -28,11 +29,7 @@ export const getUpdateApiErrorMessage = (
return maybeError.errors[0].message ?? maybeError.errors[0].error;
}
- if (typeof maybeError.data?.message === "string") {
- return maybeError.data.message;
- }
-
- return t`Unknown error`;
+ return getErrorMessage(error, t`Unknown error`);
};
export function getUpdateApiErrorType(error: unknown): string {
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LandingPageUrlField/LandingPageUrlField.tsx b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LandingPageUrlField/LandingPageUrlField.tsx
index 9ad6d8f02fb..5193f690a20 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LandingPageUrlField/LandingPageUrlField.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LandingPageUrlField/LandingPageUrlField.tsx
@@ -1,9 +1,9 @@
import { useEffect, useState } from "react";
import { t } from "ttag";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { useAdminSetting } from "metabase/settings";
import { Stack, Text, TextInput } from "metabase/ui";
-import type { GenericErrorResponse } from "metabase/utils/errors";
import { getRelativeLandingPageUrl } from "./utils";
@@ -33,11 +33,7 @@ export function LandingPageUrlField() {
});
if (result.error) {
- const message =
- // Unjustified type cast. FIXME
- (result.error as { data: GenericErrorResponse })?.data?.message ||
- t`Something went wrong`;
- setError(message);
+ setError(getErrorMessage(result.error));
}
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
index ddb0840ec34..754c3c3a4b2 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx
@@ -53,6 +53,7 @@ import type {
SdkDashboardId,
} from "embedding-sdk-bundle/types/dashboard";
import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { useConfirmation } from "metabase/common/hooks";
import { useLocale } from "metabase/common/hooks/use-locale";
import {
@@ -561,7 +562,7 @@ const SdkDashboardInner = ({
style={style}
>
<SdkError
- message={errorPage.data?.message ?? t`Something's gone wrong`}
+ message={getErrorMessage(errorPage, t`Something's gone wrong`)}
/>
</MaybeStyledWrapper>
);
diff --git a/frontend/src/metabase/AppComponent.tsx b/frontend/src/metabase/AppComponent.tsx
index 7cbb22c3b00..ace3c88d838 100644
--- a/frontend/src/metabase/AppComponent.tsx
+++ b/frontend/src/metabase/AppComponent.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { AppBarContainer } from "metabase/app/nav/AppBar";
import { Navbar } from "metabase/app/nav/Navbar";
import {
@@ -56,7 +57,7 @@ const getErrorComponent = ({ status, data, context }: AppErrorDescriptor) => {
if (data?.error_code === "archived" && context === "query-builder") {
return <Archived entityName="question" linkTo="/questions/archive" />;
}
- return <GenericError details={data?.message} />;
+ return <GenericError details={findErrorMessage(data)} />;
};
export function App() {
diff --git a/frontend/src/metabase/actions/utils.ts b/frontend/src/metabase/actions/utils.ts
index f963e6feb05..7c389f9794d 100644
--- a/frontend/src/metabase/actions/utils.ts
+++ b/frontend/src/metabase/actions/utils.ts
@@ -2,6 +2,7 @@ import { match } from "ts-pattern";
import { t } from "ttag";
import * as Yup from "yup";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { hasActionsEnabled } from "metabase/common/utils/database";
import type { ButtonProps } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
@@ -209,7 +210,7 @@ export function getActionExecutionMessage(
export function getActionErrorMessage(error: unknown) {
return (
- Errors.getResponseErrorMessage(error) ??
+ findErrorMessage(error) ??
t`Something went wrong while executing the action`
);
}
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseDataActionsSection/DataActionsSection/DataActionsSection.tsx b/frontend/src/metabase/admin/databases/components/DatabaseDataActionsSection/DataActionsSection/DataActionsSection.tsx
index ce011af5caa..cb6b98d5918 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseDataActionsSection/DataActionsSection/DataActionsSection.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseDataActionsSection/DataActionsSection/DataActionsSection.tsx
@@ -1,8 +1,8 @@
import { useState } from "react";
import { t } from "ttag";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { Alert, Box, Flex, Icon, Switch } from "metabase/ui";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import { Description, Error, Label } from "../../DatabaseFeatureComponents";
@@ -24,7 +24,7 @@ export function DataActionsSection({
setError(null);
await onToggleDataActionsEnabled(enabled);
} catch (err) {
- setError(getResponseErrorMessage(err) || t`An error occurred`);
+ setError(findErrorMessage(err) || t`An error occurred`);
}
};
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseModelPersistenceSection/ModelCachingControl/ModelCachingControl.tsx b/frontend/src/metabase/admin/databases/components/DatabaseModelPersistenceSection/ModelCachingControl/ModelCachingControl.tsx
index 0f47991ee71..4432cb50592 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseModelPersistenceSection/ModelCachingControl/ModelCachingControl.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseModelPersistenceSection/ModelCachingControl/ModelCachingControl.tsx
@@ -5,6 +5,7 @@ import {
usePersistDatabaseMutation,
useUnpersistDatabaseMutation,
} from "metabase/api";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { ExternalLink } from "metabase/common/components/ExternalLink";
import { useDocsUrl } from "metabase/common/hooks";
import { hasFeature } from "metabase/databases";
@@ -20,16 +21,6 @@ interface Props {
disabled: boolean;
}
-interface ErrorResponse {
- data?: {
- message?: string;
- };
-}
-
-function isLackPermissionsError(response: ErrorResponse) {
- return response?.data?.message?.startsWith("Lack permissions");
-}
-
export function ModelCachingControl({ database, disabled }: Props) {
const [error, setError] = useState<string | null>(null);
@@ -51,14 +42,13 @@ export function ModelCachingControl({ database, disabled }: Props) {
await persistDatabase(databaseId).unwrap();
}
} catch (error) {
- // Unjustified type cast. FIXME
- const response = error as ErrorResponse;
- if (isLackPermissionsError(response)) {
+ const message = findErrorMessage(error);
+ if (message?.startsWith("Lack permissions")) {
setError(
t`For models to be cached, the user should have create table permission or create schema permission in this database.`,
);
} else {
- setError(response.data?.message || t`An error occurred`);
+ setError(message ?? t`An error occurred`);
}
throw error;
}
diff --git a/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx b/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
index 1b3c98e23d2..377d2e1e371 100644
--- a/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
+++ b/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";
import { jt, t } from "ttag";
import { useGetDatabaseUsageInfoQuery } from "metabase/api";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useNavigate } from "metabase/router";
import {
@@ -30,20 +31,8 @@ const hasContentInDatabase = (usageInfo: DatabaseUsageInfo) => {
return entityTypesCount(usageInfo) > 0;
};
-const getErrorMessage = (error: any) => {
- if (!error) {
- return null;
- }
-
- let errorMessage = t`Server error encountered`;
- if (error.data && error.data.message) {
- errorMessage = error.data.message;
- } else if (error.message) {
- errorMessage = error.message;
- }
-
- return errorMessage;
-};
+const getDeleteErrorMessage = (error: unknown) =>
+ error ? getErrorMessage(error, t`Server error encountered`) : null;
export interface DeleteDatabaseModalProps {
opened: boolean;
@@ -102,7 +91,7 @@ export const DeleteDatabaseModal = ({
const deleteButtonLabel = t`Delete this DB connection`;
- const errorMessage = getErrorMessage(error);
+ const errorMessage = getDeleteErrorMessage(error);
const hasMoreThanOneEntityType = usageInfo && entityTypesCount(usageInfo) > 1;
const databaseNameConfirmationRef = useRef<HTMLInputElement>(null);
diff --git a/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
index d1f93a73e5d..01529cccb3a 100644
--- a/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
@@ -1,11 +1,12 @@
import { useCallback } from "react";
import { useInvalidateCacheConfigsMutation } from "metabase/api";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { useDispatch } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
import type { CacheableModel } from "metabase-types/api";
-import { isErrorWithMessage, resolveSmoothly } from "../utils";
+import { resolveSmoothly } from "../utils";
export const useInvalidateTarget = (
targetId: number | null,
@@ -30,11 +31,12 @@ export const useInvalidateTarget = (
await invalidate;
}
} catch (e) {
- if (isErrorWithMessage(e)) {
+ const message = findErrorMessage(e);
+ if (message) {
dispatch(
addUndo({
variant: "negative",
- message: e.data.message,
+ message,
}),
);
}
diff --git a/frontend/src/metabase/admin/performance/utils.tsx b/frontend/src/metabase/admin/performance/utils.tsx
index 677c15c836b..ecbdd1f41a6 100644
--- a/frontend/src/metabase/admin/performance/utils.tsx
+++ b/frontend/src/metabase/admin/performance/utils.tsx
@@ -21,19 +21,9 @@ import type {
CacheableModel,
} from "metabase-types/api";
import { CacheDurationUnit } from "metabase-types/api";
-import { isObject } from "metabase-types/guards";
import { rootId } from "./constants/simple";
-type ErrorWithMessage = { data: { message: string } };
-export const isErrorWithMessage = (error: unknown): error is ErrorWithMessage =>
- typeof error === "object" &&
- error !== null &&
- "data" in error &&
- isObject(error.data) &&
- "message" in error.data &&
- typeof error.data.message === "string";
-
const delay = (milliseconds: number) =>
new Promise((resolve) => setTimeout(resolve, milliseconds));
diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx
index b10be91fb43..a634a70f3aa 100644
--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx
+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx
@@ -3,6 +3,7 @@ import { createSelector } from "@reduxjs/toolkit";
import { msgid, ngettext, t } from "ttag";
import _ from "underscore";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { hasDbRoutingEnabled } from "metabase/common/utils/database";
import {
getSpecialGroupType,
@@ -15,7 +16,6 @@ import {
} from "metabase/plugins";
import type { State } from "metabase/redux/store";
import { getPlan, getSetting, getTokenFeature } from "metabase/settings";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import type {
Group,
GroupsPermissions,
@@ -88,7 +88,7 @@ export const getLoadingDatabaseTablesError = (
return undefined;
}
const { error } = selectDatabaseTablesMetadata(state, params.databaseId);
- return error ? getResponseErrorMessage(error) : undefined;
+ return error ? findErrorMessage(error) : undefined;
};
type RouteParamsSelectorParameters = {
diff --git a/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx b/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx
index 6b287b3ed6f..c85f113ed44 100644
--- a/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/Email/BaseSMTPConnectionForm.tsx
@@ -3,7 +3,6 @@ import { useCallback, useMemo } from "react";
import { t } from "ttag";
import * as Yup from "yup";
-import { isErrorWithMessage } from "metabase/admin/performance/utils";
import { getErrorMessage } from "metabase/api/utils";
import { useToast } from "metabase/common/hooks";
import {
@@ -123,9 +122,10 @@ export const BaseSMTPConnectionForm = ({
if (result.error) {
sendToast({
variant: "negative",
- message: isErrorWithMessage(result.error)
- ? result.error.data.message
- : t`Error clearing email settings`,
+ message: getErrorMessage(
+ result.error,
+ t`Error clearing email settings`,
+ ),
});
} else {
sendToast({
diff --git a/frontend/src/metabase/admin/settings/components/widgets/Notifications/WebhookForm.tsx b/frontend/src/metabase/admin/settings/components/widgets/Notifications/WebhookForm.tsx
index b4af1c5c828..7826da8ccac 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/Notifications/WebhookForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/Notifications/WebhookForm.tsx
@@ -4,6 +4,7 @@ import { c, jt, t } from "ttag";
import * as Yup from "yup";
import { useTestChannelMutation } from "metabase/api/channel";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { ExternalLink } from "metabase/common/components/ExternalLink";
import { useActionButtonLabel } from "metabase/common/hooks/use-action-button-label";
import {
@@ -27,7 +28,6 @@ import {
Stack,
Title,
} from "metabase/ui";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import {
type NotificationAuthMethods,
type NotificationAuthType,
@@ -221,8 +221,7 @@ export const WebhookForm = ({
},
(e) => {
setTestButtonLabel(t`Test failed`);
- const message =
- typeof e === "string" ? e : getResponseErrorMessage(e);
+ const message = findErrorMessage(e);
setFieldError("url", message);
},
diff --git a/frontend/src/metabase/admin/settings/components/widgets/SiteUrlWidget.tsx b/frontend/src/metabase/admin/settings/components/widgets/SiteUrlWidget.tsx
index 1ca6525e5fd..b4d8053721c 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/SiteUrlWidget.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/SiteUrlWidget.tsx
@@ -1,6 +1,7 @@
import { useState } from "react";
import { t } from "ttag";
+import { getErrorMessage } from "metabase/api/utils/errors";
import { InputWithSelectPrefix } from "metabase/common/components/InputWithSelectPrefix";
import { useHasTokenFeature } from "metabase/common/hooks";
import { useAdminSetting } from "metabase/settings";
@@ -9,7 +10,6 @@ import {
SettingHeader,
} from "metabase/settings-components";
import { Box, Text } from "metabase/ui";
-import type { GenericErrorResponse } from "metabase/utils/errors";
export function SiteUrlWidget() {
const { value, updateSetting, description, isLoading, settingDetails } =
@@ -24,11 +24,9 @@ export function SiteUrlWidget() {
updateSetting({ key: "site-url", value: newValue }).then((response) => {
setErrorMessage("");
if (response?.error) {
- const message =
- // Unjustified type cast. FIXME
- (response.error as { data: GenericErrorResponse })?.data?.message ||
- t`Error saving Site URL`;
- setErrorMessage(message);
+ setErrorMessage(
+ getErrorMessage(response.error, t`Error saving Site URL`),
+ );
}
});
};
diff --git a/frontend/src/metabase/api/utils/errors.ts b/frontend/src/metabase/api/utils/errors.ts
index 18709a20054..d16f736b187 100644
--- a/frontend/src/metabase/api/utils/errors.ts
+++ b/frontend/src/metabase/api/utils/errors.ts
@@ -1,46 +1,71 @@
import { t } from "ttag";
+import { isObject } from "metabase-types/guards/common";
+
export type ErrorPayload =
| { message: string }
| { error: string }
| { error_message: string }
| string;
-export const getErrorMessage = (
- payload:
- | unknown
- | ErrorPayload
- | { data: ErrorPayload }
- | { error: ErrorPayload },
- fallback: string = t`Something went wrong`,
-): string => {
+/**
+ * The human-readable message in an API error, whatever shape it arrived in, or `undefined` when it has none.
+ *
+ * An error body is either the message itself or an object carrying it under `message`, `error`, `error_message` or
+ * `cause`, with validation failures under `errors`. RTK Query results and thrown responses wrap the body under
+ * `data`, and a nested `error` may itself be such a wrapper. The lookup recurses through all of these, so callers
+ * don't depend on the exact shape of a response. A structured body is the most specific source and wins over the
+ * error's own message; a plain-string body is the last resort.
+ */
+export const findErrorMessage = (payload: unknown): string | undefined => {
if (typeof payload === "string") {
- return payload || fallback;
+ return payload || undefined;
}
- if (!payload || typeof payload !== "object") {
- return fallback;
+ if (!isObject(payload)) {
+ return undefined;
}
- if ("message" in payload && !isEmpty(payload.message)) {
- return getErrorMessage(payload.message, fallback);
- }
-
- if ("error" in payload && !isEmpty(payload.error)) {
- return getErrorMessage(payload.error, fallback);
- }
+ const body = isObject(payload.data) ? payload.data : undefined;
+ const stringBody =
+ typeof payload.data === "string" ? payload.data : undefined;
- if ("error_message" in payload && !isEmpty(payload.error_message)) {
- return getErrorMessage(payload.error_message, fallback);
- }
+ return (
+ findErrorMessage(body) ??
+ findErrorMessage(payload.message) ??
+ findErrorMessage(payload.error) ??
+ findErrorMessage(payload.error_message) ??
+ findErrorMessage(payload.cause) ??
+ findValidationMessage(payload.errors) ??
+ findErrorMessage(stringBody)
+ );
+};
- if ("data" in payload && !isEmpty(payload.data)) {
- return getErrorMessage(payload.data, fallback);
+/**
+ * Validation failures arrive as a map from field name to message, with a whole-form message under `_error`, or as
+ * a list of error objects. Field messages are fragments meant for the field they belong to, so only the whole-form
+ * ones count as the error's message.
+ */
+const findValidationMessage = (errors: unknown): string | undefined => {
+ if (Array.isArray(errors)) {
+ for (const error of errors) {
+ const message = findErrorMessage(error);
+ if (message !== undefined) {
+ return message;
+ }
+ }
+ return undefined;
}
- return fallback;
+ return isObject(errors) ? findErrorMessage(errors._error) : undefined;
};
+/** [[findErrorMessage]] with `fallback` when the error has no message. */
+export const getErrorMessage = (
+ payload: unknown,
+ fallback: string = t`Something went wrong`,
+): string => findErrorMessage(payload) ?? fallback;
+
type RequestError = {
status?: number;
data?: { error_code?: string; errors?: Record<string, unknown> };
@@ -53,7 +78,3 @@ const isRequestError = (error: unknown): error is RequestError =>
// `error_code`. Prefer the stable code over the localized field message.
export const isEmailAlreadyInUse = (error: unknown): boolean =>
isRequestError(error) && error.data?.error_code === "email-already-in-use";
-
-function isEmpty(value: unknown): boolean {
- return value == null || value === "";
-}
diff --git a/frontend/src/metabase/api/utils/errors.unit.spec.ts b/frontend/src/metabase/api/utils/errors.unit.spec.ts
index feb79b79db6..3c5637d2225 100644
--- a/frontend/src/metabase/api/utils/errors.unit.spec.ts
+++ b/frontend/src/metabase/api/utils/errors.unit.spec.ts
@@ -1,4 +1,8 @@
-import { getErrorMessage, isEmailAlreadyInUse } from "./errors";
+import {
+ findErrorMessage,
+ getErrorMessage,
+ isEmailAlreadyInUse,
+} from "./errors";
describe("getErrorMessage", () => {
it("should return a message from a string payload", () => {
@@ -52,6 +56,81 @@ describe("getErrorMessage", () => {
const result = getErrorMessage(null);
expect(result).toEqual("Something went wrong");
});
+
+ it("should return the whole-form message under errors._error", () => {
+ const result = getErrorMessage({
+ data: { errors: { _error: "Invalid credentials" } },
+ });
+ expect(result).toEqual("Invalid credentials");
+ });
+
+ it("should not use a field-level validation message as the error message", () => {
+ const result = getErrorMessage(
+ { data: { errors: { password: "too short" } } },
+ "Fallback message",
+ );
+ expect(result).toEqual("Fallback message");
+ });
+
+ it("should return the first message in a list of errors", () => {
+ const result = getErrorMessage({
+ errors: [{ error: "First failure" }, { message: "Second failure" }],
+ });
+ expect(result).toEqual("First failure");
+ });
+
+ it("should prefer the message in a structured body over the error's own message", () => {
+ const result = getErrorMessage({
+ message: "Request failed",
+ data: { message: "Server message" },
+ });
+ expect(result).toEqual("Server message");
+ });
+
+ it("should prefer the error's own message over a plain-string body", () => {
+ const result = getErrorMessage({
+ message: "Request failed",
+ data: "Server message",
+ });
+ expect(result).toEqual("Request failed");
+ });
+
+ it("should prefer a whole-form message in the body over the error's own message", () => {
+ const result = getErrorMessage({
+ message: "Request failed",
+ data: { errors: { _error: "Invalid credentials" } },
+ });
+ expect(result).toEqual("Invalid credentials");
+ });
+
+ it("should fall back to the error's own message when the body is empty", () => {
+ const result = getErrorMessage({ message: "Request failed", data: {} });
+ expect(result).toEqual("Request failed");
+ });
+
+ it("should return the cause of an error", () => {
+ const result = getErrorMessage({ cause: "Root cause" });
+ expect(result).toEqual("Root cause");
+ });
+
+ it("should look inside a nested error wrapper", () => {
+ const result = getErrorMessage({
+ error: { status: 400, data: "Nested message" },
+ });
+ expect(result).toEqual("Nested message");
+ });
+});
+
+describe("findErrorMessage", () => {
+ it("should return undefined when the error carries no message", () => {
+ expect(findErrorMessage({ status: 500 })).toBeUndefined();
+ expect(findErrorMessage("")).toBeUndefined();
+ expect(findErrorMessage(undefined)).toBeUndefined();
+ });
+
+ it("should return the message of a thrown Error", () => {
+ expect(findErrorMessage(new Error("Boom"))).toEqual("Boom");
+ });
});
describe("isEmailAlreadyInUse", () => {
diff --git a/frontend/src/metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper.tsx b/frontend/src/metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper.tsx
index 8cb1e1f3736..076d573cd83 100644
--- a/frontend/src/metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper.tsx
+++ b/frontend/src/metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper.tsx
@@ -10,6 +10,7 @@ import {
} from "react";
import { t } from "ttag";
+import { findErrorMessage } from "metabase/api/utils/errors";
import CS from "metabase/css/core/index.css";
import { Loader } from "metabase/ui";
@@ -67,18 +68,9 @@ export const LoadingAndErrorWrapper = forwardRef<
});
function getErrorMessage() {
- let errorMessage =
- // NOTE Atte Keinänen 5/10/17 Dashboard API endpoint returns the error as JSON with `message` field
- error &&
- ((error.data?.message ? error.data.message : error.data) ||
- error.statusText ||
- error.message ||
- error);
-
- if (!errorMessage || typeof errorMessage !== "string") {
- errorMessage = t`An error occurred`;
- }
- return errorMessage;
+ const statusText =
+ typeof error?.statusText === "string" ? error.statusText : undefined;
+ return findErrorMessage(error) ?? statusText ?? t`An error occurred`;
}
function renderError(contentClassName: string) {
diff --git a/frontend/src/metabase/forms/hooks/use-form-submit/use-form-submit.ts b/frontend/src/metabase/forms/hooks/use-form-submit/use-form-submit.ts
index a6b15cada71..4dc37290837 100644
--- a/frontend/src/metabase/forms/hooks/use-form-submit/use-form-submit.ts
+++ b/frontend/src/metabase/forms/hooks/use-form-submit/use-form-submit.ts
@@ -2,7 +2,7 @@ import type { FormikHelpers } from "formik";
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useState } from "react";
-import { getResponseErrorMessage } from "metabase/utils/errors";
+import { findErrorMessage } from "metabase/api/utils/errors";
import type { FormState } from "../../contexts";
@@ -61,6 +61,6 @@ const getFormErrors = (error: unknown) => {
const getFormMessage = (error: unknown) => {
if (isFormError(error)) {
- return getResponseErrorMessage(error);
+ return findErrorMessage(error);
}
};
diff --git a/frontend/src/metabase/monitor/tools/components/Logs/hooks.ts b/frontend/src/metabase/monitor/tools/components/Logs/hooks.ts
index 8723452bcdc..125d7fbc23b 100644
--- a/frontend/src/metabase/monitor/tools/components/Logs/hooks.ts
+++ b/frontend/src/metabase/monitor/tools/components/Logs/hooks.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useListLogsQuery } from "metabase/api/logger";
+import { findErrorMessage } from "metabase/api/utils/errors";
import type { Log } from "metabase-types/api";
import { maybeMergeLogs } from "./utils";
@@ -24,12 +25,7 @@ export function usePollingLogsQuery(pollingDurationMs: number) {
if (!queryError) {
return null;
}
- // Unjustified type cast. FIXME
- const errorWithData = queryError as {
- data?: { message?: string };
- message?: string;
- };
- return errorWithData.data?.message ?? errorWithData.message ?? null;
+ return findErrorMessage(queryError) ?? null;
}, [queryError]);
return { loaded: isSuccess, error, logs };
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index 782cd8f12fe..dbc43c83d6b 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -10,6 +10,7 @@ import {
useSendUnsavedNotificationMutation,
useUpdateNotificationMutation,
} from "metabase/api";
+import { findErrorMessage } from "metabase/api/utils/errors";
import type { ScheduleValueType } from "metabase/common/components/Schedule/domain";
import CS from "metabase/css/core/index.css";
import {
@@ -41,7 +42,6 @@ import {
Text,
rem,
} from "metabase/ui";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import type Question from "metabase-lib/v1/Question";
import type {
AdminNotification,
@@ -211,7 +211,7 @@ export const CreateOrEditQuestionAlertModal = ({
if (result.error) {
const errorText =
- getResponseErrorMessage(result.error) ?? t`An error occurred`;
+ findErrorMessage(result.error) ?? t`An error occurred`;
dispatch(
addUndo({
@@ -247,7 +247,7 @@ export const CreateOrEditQuestionAlertModal = ({
dispatch(
addUndo({
variant: "negative",
- message: t`Failed to send test alert. ${getResponseErrorMessage(result.error) ?? t`An error occurred`}`,
+ message: t`Failed to send test alert. ${findErrorMessage(result.error) ?? t`An error occurred`}`,
}),
);
}
diff --git a/frontend/src/metabase/notifications/pulse/actions.ts b/frontend/src/metabase/notifications/pulse/actions.ts
index b4f3509ed6c..cad522c67b4 100644
--- a/frontend/src/metabase/notifications/pulse/actions.ts
+++ b/frontend/src/metabase/notifications/pulse/actions.ts
@@ -2,9 +2,9 @@ import { createAction } from "redux-actions";
import { t } from "ttag";
import { subscriptionApi } from "metabase/api";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { createThunkAction } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
-import { getResponseErrorMessage } from "metabase/utils/errors";
import type {
ChannelApiResponse,
CreateSubscriptionRequest,
@@ -56,7 +56,7 @@ export const saveEditingPulse = createThunkAction(
}
} catch (error) {
const errorMessage =
- getResponseErrorMessage(error) ??
+ findErrorMessage(error) ??
t`Something went wrong while saving your subscription`;
dispatch(
diff --git a/frontend/src/metabase/redux/uploads.ts b/frontend/src/metabase/redux/uploads.ts
index bcb79b248cf..763acc8cb66 100644
--- a/frontend/src/metabase/redux/uploads.ts
+++ b/frontend/src/metabase/redux/uploads.ts
@@ -3,6 +3,7 @@ import { t } from "ttag";
import { Api, cardApi, tableApi } from "metabase/api";
import { listTag } from "metabase/api/tags";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import type { Dispatch, State } from "metabase/redux/store";
import type { FileUploadState } from "metabase/redux/store/upload";
@@ -167,7 +168,7 @@ export const uploadFile = createThunkAction(
dispatch(
uploadError({
id,
- error: err?.data?.message ?? err?.data,
+ error: findErrorMessage(err) ?? err?.data,
}),
);
}
diff --git a/frontend/src/metabase/selectors/app.ts b/frontend/src/metabase/selectors/app.ts
index b7861259df3..3673e1e2f2c 100644
--- a/frontend/src/metabase/selectors/app.ts
+++ b/frontend/src/metabase/selectors/app.ts
@@ -1,6 +1,7 @@
import type { Selector } from "@reduxjs/toolkit";
import { createSelector } from "@reduxjs/toolkit";
+import { findErrorMessage } from "metabase/api/utils/errors";
import { getUser } from "metabase/current-user";
import { getEmbedOptions } from "metabase/embedding/interactive-embedding";
import type { State } from "metabase/redux/store";
@@ -21,7 +22,7 @@ export const getDetailViewState = (state: State) => {
export const getErrorMessage = (state: State) => {
const errorPage = getErrorPage(state);
- return errorPage?.data?.message || errorPage?.data;
+ return findErrorMessage(errorPage?.data) ?? errorPage?.data;
};
export const getIsNavbarOpen: Selector<State, boolean> = createSelector(
diff --git a/frontend/src/metabase/settings/use-admin-setting.ts b/frontend/src/metabase/settings/use-admin-setting.ts
index 680bce0fe2a..d7731c50abe 100644
--- a/frontend/src/metabase/settings/use-admin-setting.ts
+++ b/frontend/src/metabase/settings/use-admin-setting.ts
@@ -89,10 +89,10 @@ export const useAdminSetting = <SettingName extends EnterpriseSettingKey>(
}
if (response.error) {
- const message =
- // Unjustified type cast. FIXME
- (response.error as { data?: { message: string } })?.data?.message ||
- t`Error saving settings`;
+ const message = getErrorMessage(
+ response.error,
+ t`Error saving settings`,
+ );
sendToast({
message,
@@ -153,10 +153,10 @@ export const useAdminSettings = <
if (toast) {
if (response.error) {
- const message =
- // Unjustified type cast. FIXME
- (response.error as { data?: { message: string } })?.data?.message ||
- t`Error saving settings`;
+ const message = getErrorMessage(
+ response.error,
+ t`Error saving settings`,
+ );
sendToast({
message,
diff --git a/frontend/src/metabase/utils/errors/messages.ts b/frontend/src/metabase/utils/errors/messages.ts
index ca8df2a63e3..c6c1d030acb 100644
--- a/frontend/src/metabase/utils/errors/messages.ts
+++ b/frontend/src/metabase/utils/errors/messages.ts
@@ -1,36 +1,3 @@
-import type { GenericErrorResponse } from "./types";
-
-/**
- * @deprecated Use `getErrorMessage` from `metabase/api/utils` instead.
- */
-export function getResponseErrorMessage(error: unknown): string | undefined {
- // Unjustified type cast. FIXME
- const response = error as GenericErrorResponse | undefined;
-
- if (!response) {
- return undefined;
- }
-
- if (typeof response.data === "object") {
- if (typeof response.data?.message === "string") {
- return response.data.message;
- }
- if (typeof response.data?.errors?._error === "string") {
- return response.data.errors?._error;
- }
- }
-
- if (response.message) {
- return response.message;
- }
-
- if (typeof response.data === "string") {
- return response.data;
- }
-
- return undefined;
-}
-
export function isResourceNotFoundError(error: any) {
return error instanceof Object && "status" in error && error.status === 404;
}
diff --git a/frontend/src/metabase/utils/errors/messages.unit.spec.ts b/frontend/src/metabase/utils/errors/messages.unit.spec.ts
deleted file mode 100644
index 5a1ca7a7dcd..00000000000
--- a/frontend/src/metabase/utils/errors/messages.unit.spec.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { merge } from "icepick";
-
-import { getResponseErrorMessage } from "./messages";
-
-const ERROR_DATA_MESSAGE = {
- data: {
- message: "Error from error.data.message",
- },
-};
-
-const ERROR_DATA_ERRORS_ERROR = {
- data: {
- errors: {
- _error: "Error from error.data.errors._error",
- },
- },
-};
-
-const ERROR_MESSAGE = {
- message: "Error from error.message",
-};
-
-const ERROR_DATA = {
- data: "Error from error.data",
-};
-
-describe("core/utils/errors/messages", () => {
- describe("getResponseErrorMessage", () => {
- it("returns undefined if can't find a message", () => {
- expect(getResponseErrorMessage({})).toBeUndefined();
- });
-
- it("returns error.data.message", () => {
- const response = merge(
- ERROR_DATA_MESSAGE,
- merge(ERROR_DATA_ERRORS_ERROR, ERROR_MESSAGE),
- );
-
- const message = getResponseErrorMessage(response);
-
- expect(message).toEqual("Error from error.data.message");
- });
-
- it("returns error.data.errors._error", () => {
- const response = merge(ERROR_DATA_ERRORS_ERROR, ERROR_MESSAGE);
- const message = getResponseErrorMessage(response);
- expect(message).toEqual("Error from error.data.errors._error");
- });
-
- it("returns error.message", () => {
- const response = merge(ERROR_MESSAGE, ERROR_DATA);
- const message = getResponseErrorMessage(response);
- expect(message).toEqual("Error from error.message");
- });
-
- it("returns error.data", () => {
- const message = getResponseErrorMessage(ERROR_DATA);
- expect(message).toEqual("Error from error.data");
- });
-
- it("handles empty data object", () => {
- const response = {
- data: {},
- message: "Error from error.message",
- };
- const message = getResponseErrorMessage(response);
- expect(message).toBe("Error from error.message");
- });
-
- it("ignores field-specific errors", () => {
- const response = {
- data: {
- errors: {
- firstName: "Required",
- password: "Too short",
- },
- },
- };
- const message = getResponseErrorMessage(response);
- expect(message).toBeUndefined();
- });
- });
-});
diff --git a/src/metabase/agent_lib/representations.clj b/src/metabase/agent_lib/representations.clj
index ff3de211f66..e3ca85b32f0 100644
--- a/src/metabase/agent_lib/representations.clj
+++ b/src/metabase/agent_lib/representations.clj
@@ -83,11 +83,12 @@
decoded (mc/decode schema external-query mtx/string-transformer)]
(when-let [error (mr/explain ::lib.schema/external-query decoded)]
(throw (ex-info (tru "External query has an invalid structure.")
- {:status-code 400
- :error :invalid-external-query
- :humanized (mu.humanize/humanize error)
- :details (pr-str (mu.humanize/humanize error))
- :schema ::lib.schema/external-query})))
+ {:status-code 400
+ :error :invalid-external-query
+ :humanized (mu.humanize/humanize error)
+ :details (pr-str (mu.humanize/humanize error))
+ :schema ::lib.schema/external-query
+ :response/keys #{:humanized :details}})))
decoded))
(def ^:private known-stage-keys
@@ -118,11 +119,12 @@
stage-idx
(pr-str (vec unknown))
(pr-str (vec (sort known-stage-keys))))
- {:status-code 400
- :error :unknown-stage-key
- :agent-error? true
- :stage-index stage-idx
- :unknown-keys (vec unknown)})))))
+ {:status-code 400
+ :error :unknown-stage-key
+ :agent-error? true
+ :stage-index stage-idx
+ :unknown-keys (vec unknown)
+ :response/keys #{:unknown-keys}})))))
;;; ============================================================
;;; Repair-pipeline schema (string-keyed portable form)
@@ -231,9 +233,10 @@
[parsed]
(when-let [error (mr/explain query-schema parsed)]
(throw (ex-info (tru "Representations query has an invalid structure.")
- {:status-code 400
- :error :invalid-representations-query
- :humanized (mu.humanize/humanize error)
- :details (pr-str (mu.humanize/humanize error))
- :schema ::query})))
+ {:status-code 400
+ :error :invalid-representations-query
+ :humanized (mu.humanize/humanize error)
+ :details (pr-str (mu.humanize/humanize error))
+ :schema ::query
+ :response/keys #{:humanized :details}})))
parsed)
diff --git a/src/metabase/api/common.clj b/src/metabase/api/common.clj
index 93848b4b0d7..abb557d2d6d 100644
--- a/src/metabase/api/common.clj
+++ b/src/metabase/api/common.clj
@@ -86,6 +86,7 @@
[metabase.events.core :as events]
[metabase.models.interface :as mi]
[metabase.util :as u]
+ [metabase.util.api-error :as api-error]
[metabase.util.i18n :as i18n :refer [deferred-tru tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -152,7 +153,9 @@
(not (i18n/localized-string? message)))
[(:message message) message]
[message])]
- (throw (ex-info (str message) (assoc info :status-code code)))))
+ ;; a map message is authored as the response body, so all of it is client-facing
+ (throw (ex-info (str message)
+ (apply api-error/extend-response-keys (assoc info :status-code code) (keys info))))))
condition)
(defn check
diff --git a/src/metabase/api/macros.clj b/src/metabase/api/macros.clj
index 937e2d4006f..fa845ac017c 100644
--- a/src/metabase/api/macros.clj
+++ b/src/metabase/api/macros.clj
@@ -530,24 +530,23 @@
(let [params (or params {})
decoded ((decoder schema) params)]
(when-not (mr/validate schema decoded)
- (throw (ex-info (format "Invalid %s" (case params-type
- :route "route parameters"
- :query "query parameters"
- :body "body"
- :request "request"
- ;; fall back to the keyword name for any other validated
- ;; params-type so we never throw "No matching clause" here
- (name params-type)))
- (let [explanation (mr/explain schema decoded)
- specific-errors (invalid-params-specific-errors explanation)
- errors (invalid-params-errors explanation)]
+ (let [explanation (mr/explain schema decoded)]
+ (throw (ex-info (format "Invalid %s" (case params-type
+ :route "route parameters"
+ :query "query parameters"
+ :body "body"
+ :request "request"
+ ;; fall back to the keyword name for any other validated
+ ;; params-type so we never throw "No matching clause" here
+ (name params-type)))
{:status-code 400
#_:api/debug #_{:params-type params-type
- :schema (mc/form schema)
- :params params
- :decoded decoded}
- :specific-errors specific-errors
- :errors errors}))))
+ :schema (mc/form schema)
+ :params params
+ :decoded decoded}
+ :specific-errors (invalid-params-specific-errors explanation)
+ :errors (invalid-params-errors explanation)
+ :response/keys #{:specific-errors}}))))
decoded))
(mu/defn- decode-and-validate-params-form
diff --git a/src/metabase/channel/impl/http.clj b/src/metabase/channel/impl/http.clj
index 981be90ec70..900ecc07be2 100644
--- a/src/metabase/channel/impl/http.clj
+++ b/src/metabase/channel/impl/http.clj
@@ -95,8 +95,10 @@
(let [data (ex-data e)]
;; throw an appropriate error if it's a connection error
(if (= ::http/unexceptional-status (:type data))
- (throw (ex-info (tru "Failed to connect to channel") {:request-status (:status data)
- :request-body (maybe-parse-json (:body data))}))
+ (throw (ex-info (tru "Failed to connect to channel")
+ {:request-status (:status data)
+ :request-body (maybe-parse-json (:body data))
+ :response/keys #{:request-status :request-body}}))
(throw e))))))
;; ------------------------------------------------------------------------------------------------;;
diff --git a/src/metabase/channel/rest/api/channel.clj b/src/metabase/channel/rest/api/channel.clj
index 0e3be6114f4..faebf8def42 100644
--- a/src/metabase/channel/rest/api/channel.clj
+++ b/src/metabase/channel/rest/api/channel.clj
@@ -12,6 +12,7 @@
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
[metabase.util :as u]
+ [metabase.util.api-error :as api-error]
[metabase.util.i18n :refer [deferred-tru tru]]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
@@ -127,7 +128,7 @@
(catch Exception e
{:status 400
:body {:message (ex-message e)
- :data (ex-data e)}})))
+ :data (api-error/response-data (ex-data e))}})))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/channel/rest/api/slack.clj b/src/metabase/channel/rest/api/slack.clj
index 2911bb31801..de8999c2b15 100644
--- a/src/metabase/channel/rest/api/slack.clj
+++ b/src/metabase/channel/rest/api/slack.clj
@@ -15,6 +15,7 @@
[metabase.slackbot.api :as slackbot]
[metabase.slackbot.config :as slackbot.config]
[metabase.system.core :as system]
+ [metabase.util.api-error :as api-error]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -131,7 +132,7 @@
(channel.settings/slack-bug-report-channel! processed-bug-channel)))
{:ok true}
(catch clojure.lang.ExceptionInfo info
- {:status 400, :body (ex-data info)})))
+ {:status 400, :body (api-error/response-data (ex-data info))})))
(def SlackManifest
"Malli schema for Slack app manifest. OSS uses a simple manifest, while EE with metabot-v3
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 6bc25ac73ac..5593a8dca28 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -1540,7 +1540,8 @@
(when-let [non-remote-synced-deps (not-empty (non-remote-synced-dependencies model))]
(throw (ex-info (str (deferred-tru "Uses content that is not remote synced."))
{:non-remote-synced-models non-remote-synced-deps
- :status-code 400})))
+ :status-code 400
+ :response/keys #{:non-remote-synced-models}})))
model)
(defn check-remote-synced-dependents
@@ -1555,7 +1556,8 @@
(when-let [remote-synced-deps (not-empty (remote-synced-dependents model))]
(throw (ex-info (str (deferred-tru "Used by remote synced content."))
{:remote-synced-models remote-synced-deps
- :status-code 400})))
+ :status-code 400
+ :response/keys #{:remote-synced-models}})))
model)
(defn moving-into-remote-synced?
@@ -2365,7 +2367,8 @@
(throw (ex-info msg {:status-code 400
:errors {:collection_id msg}
:allowed-namespaces allowed-namespaces
- :collection-namespace collection-namespace})))))))
+ :collection-namespace collection-namespace
+ :response/keys #{:allowed-namespaces :collection-namespace}})))))))
(defn annotate-collections
"Annotate collections with `:below` and `:here` keys to indicate which types are in their subtree and which types are
diff --git a/src/metabase/eid_translation/util.clj b/src/metabase/eid_translation/util.clj
index 7ff4ff6af32..1df3393f888 100644
--- a/src/metabase/eid_translation/util.clj
+++ b/src/metabase/eid_translation/util.clj
@@ -148,7 +148,8 @@
(me/with-spell-checking
(mr/explain ModelToEntityIds model-key->entity-ids)))
:allowed-models (sort (keys api-name->model))
- :status-code 400})))
+ :status-code 400
+ :response/keys #{:explanation :allowed-models}})))
(u/prog1 (into {}
(mapcat
(fn [[model eids]] (entity-ids->id-for-model model eids))
diff --git a/src/metabase/indexed_entities/api.clj b/src/metabase/indexed_entities/api.clj
index 2848a25257b..d2a863940fc 100644
--- a/src/metabase/indexed_entities/api.clj
+++ b/src/metabase/indexed_entities/api.clj
@@ -29,7 +29,8 @@
{:status-code 400
:expected-type t
:type (:effective_type field)
- :field (:name field)}))))
+ :field (:name field)
+ :response/keys #{:expected-type :field}}))))
(throw (ex-info (tru "Could not identify field by ref {0}" ref)
{:status-code 400
:ref ref
diff --git a/src/metabase/llm/provider.clj b/src/metabase/llm/provider.clj
index 3287fed6bdb..61146dbffc7 100644
--- a/src/metabase/llm/provider.clj
+++ b/src/metabase/llm/provider.clj
@@ -562,7 +562,7 @@
"Run one field's `:validate` hook against the value `config` supplies for it, if it has both."
[{:keys [key validate]} config]
(when-let [problem (and validate (some-> (u/trimmed-string (get config key)) validate))]
- (throw (ex-info (str problem) {:status-code 400 :field key}))))
+ (throw (ex-info (str problem) {:status-code 400 :field key :response/keys #{:field}}))))
(defn- field-descriptor
"`type-name`'s registry entry for `field-key`."
@@ -591,14 +591,14 @@
(let [value (u/trimmed-string (get config key))]
(when (and required? (not value) (not default))
(throw (ex-info (tru "{0} is required for {1}." (str label) type-name)
- {:status-code 400 :field key})))
+ {:status-code 400 :field key :response/keys #{:field}})))
(when (and value prefix (not (str/starts-with? value prefix)))
(throw (ex-info (cond-> (tru "Invalid {0} for {1}. It must start with ''{2}''." (str label) type-name prefix)
prefix-help (str " " prefix-help))
- {:status-code 400 :field key})))
+ {:status-code 400 :field key :response/keys #{:field}})))
(when (and value (seq options) (not-any? #(= value (:value %)) options))
(throw (ex-info (tru "Invalid {0} for {1}." (str label) type-name)
- {:status-code 400 :field key})))
+ {:status-code 400 :field key :response/keys #{:field}})))
(validate-field-value! field config)))
(defn- validate-config-field!
@@ -976,10 +976,11 @@
(throw (ex-info (tru "{0} points this connection at another server, so its credentials have to come from the environment as well. Set {1} to keep using it."
(get (connection-env-vars type-name) :base-url "The environment")
(get (connection-env-vars type-name) field "the matching environment variable"))
- {:status-code 400
- :api-error true
- :error-code :llm-credentials-must-come-from-env
- :field field}))))
+ {:status-code 400
+ :api-error true
+ :error-code :llm-credentials-must-come-from-env
+ :field field
+ :response/keys #{:field}}))))
(defn env-overlay-config
"What the environment supplies for a connection of `type-name` stored under `conn-key`, or nil where it
@@ -1260,11 +1261,12 @@
:else
(tru "Enter this connection''s credentials again to point it at a different base URL."))
- {:status-code 400
- :api-error true
- :error-code :llm-base-url-change-requires-credentials
- :field :base-url
- :secrets (mapv name missing-secrets)})))))))
+ {:status-code 400
+ :api-error true
+ :error-code :llm-base-url-change-requires-credentials
+ :field :base-url
+ :secrets (mapv name missing-secrets)
+ :response/keys #{:field}})))))))
(defn- assert-credential-write-authorized!
"Reject adding a secret to a connection sitting on a base URL this API cannot show the caller.
@@ -1284,10 +1286,11 @@
(not= base-url (:base-url (with-field-defaults type-name {})))
(not (contains? (set env-fields) :base-url)))
(throw (ex-info (tru "This connection has its own base URL. Use the provider connection settings to enter its credentials.")
- {:status-code 400
- :api-error true
- :error-code :llm-credential-change-requires-connection-settings
- :field field}))))))
+ {:status-code 400
+ :api-error true
+ :error-code :llm-credential-change-requires-connection-settings
+ :field field
+ :response/keys #{:field}}))))))
(defn set-single-provider-setting!
"Write `new-value` for the per-provider credential setting `setting-kw` into the connection its settings group
@@ -1319,10 +1322,11 @@
;; later removed that variable, carrying any stored credentials to a URL the API caller planted
;; earlier.
(throw (ex-info (tru "This connection''s base URL comes from an environment variable. Change it there.")
- {:status-code 400
- :api-error true
- :error-code :llm-base-url-is-env-managed
- :field :base-url})))
+ {:status-code 400
+ :api-error true
+ :error-code :llm-base-url-is-env-managed
+ :field :base-url
+ :response/keys #{:field}})))
(let [current-config (or (:config live) {})
new-config (if value
(assoc current-config field value)
diff --git a/src/metabase/metabot/self/ollama/connection.clj b/src/metabase/metabot/self/ollama/connection.clj
index 2f23b56425e..eac063f5222 100644
--- a/src/metabase/metabot/self/ollama/connection.clj
+++ b/src/metabase/metabot/self/ollama/connection.clj
@@ -36,10 +36,11 @@
;; `provider-client-error?` needs a numeric status to render this under the field; without one the
;; admin gets a 500.
(ex-info (tru "No Ollama base URL is set. Give the address of your server, or https://ollama.com/v1 for Ollama Cloud.")
- {:api-error true
- :status-code 400
- :field :base-url
- :error-code :base-url-missing}))
+ {:api-error true
+ :status-code 400
+ :field :base-url
+ :error-code :base-url-missing
+ :response/keys #{:field}}))
(mu/defn base-url :- :string
"The address to call.
diff --git a/src/metabase/notification/send.clj b/src/metabase/notification/send.clj
index 63d80c15f16..1f8739210ec 100644
--- a/src/metabase/notification/send.clj
+++ b/src/metabase/notification/send.clj
@@ -169,7 +169,9 @@
;; the API returns the message and the ex-data to the user, and a raw reason can name the mail host or a webhook URL
(let [failures (:failed-handlers (ex-data e))]
(ex-info (tru "Failed to deliver to {0}" (str/join ", " (distinct (map handler->channel-name failures))))
- (assoc (ex-data e) :failed-handlers (mapv #(dissoc % :message) failures))
+ (assoc (ex-data e)
+ :failed-handlers (mapv #(dissoc % :message) failures)
+ :response/keys #{:failed-handlers})
e)))
(defn- hydrate-notification
diff --git a/src/metabase/parameters/params.clj b/src/metabase/parameters/params.clj
index f1f99b6fbda..e46c36e71bb 100644
--- a/src/metabase/parameters/params.clj
+++ b/src/metabase/parameters/params.clj
@@ -58,7 +58,7 @@
(throw (ex-info (str ":parameters must be a sequence of maps with :id and :type keys; "
(pr-str (me/humanize error)))
{:parameters parameters
- :errors (:errors error)})))))
+ :errors (me/humanize error)})))))
(defn assert-valid-parameter-mappings
"Receive a Parameterized Object and check if its parameters is valid."
@@ -67,7 +67,7 @@
(when-not (mr/validate schema parameter-mappings)
(throw (ex-info ":parameter_mappings must be a sequence of maps with :parameter_id and :type keys"
{:parameter_mappings parameter-mappings
- :errors (:errors (mr/explain schema parameter-mappings))})))))
+ :errors (me/humanize (mr/explain schema parameter-mappings))})))))
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(def ^:dynamic *ignore-current-user-perms-and-return-all-field-values*
diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.clj
index 0e1e8b19498..baf803453e3 100644
--- a/src/metabase/premium_features/token_check.clj
+++ b/src/metabase/premium_features/token_check.clj
@@ -627,7 +627,9 @@
(when-not (or (mr/validate [:re RemoteCheckedToken] new-value)
(mr/validate [:re AirgapToken] new-value))
(throw (ex-info (tru "Token format is invalid.")
- {:status-code 400, :error-details "Token should be 64 hexadecimal characters."})))
+ {:status-code 400
+ :error-details "Token should be 64 hexadecimal characters."
+ :response/keys #{:error-details}})))
;; validate against the store, not a cached verdict — the token may be the same string with a
;; renewed subscription behind it
(clear-cache!)
@@ -639,7 +641,8 @@
;; probably more appropriate.
:status-code (if (:canonical? decoded)
400
- 503)}))))
+ 503)
+ :response/keys #{:error-details}}))))
(log/info "Token is valid."))
(setting/set-value-of-type! :string :premium-embedding-token new-value)
(events/publish-event! :event/set-premium-embedding-token {})
@@ -737,7 +740,7 @@
[feature-name]
(ex-info (tru "{0} is a paid feature not currently available to your instance. Please upgrade to use it. Learn more at metabase.com/upgrade/"
feature-name)
- {:status-code 402 :status "error-premium-feature-not-available"}))
+ {:status-code 402 :status "error-premium-feature-not-available" :response/keys #{:status}}))
(mu/defn assert-has-feature
"Check if an token with `feature` is present. If not, throw an error with a message using `feature-name`.
diff --git a/src/metabase/pulse/send.clj b/src/metabase/pulse/send.clj
index f9707c5bb4f..44119c6559e 100644
--- a/src/metabase/pulse/send.clj
+++ b/src/metabase/pulse/send.clj
@@ -124,7 +124,8 @@
{:status-code 502
:error-code :notification/delivery-failed
:notification-id (:id pulse)
- :failed-handlers failed-handlers})))
+ :failed-handlers failed-handlers
+ :response/keys #{:failed-handlers}})))
(defn- send-pulse!*
[{:keys [channels channel-ids] :as pulse} dashboard async?]
diff --git a/src/metabase/query_permissions/impl.clj b/src/metabase/query_permissions/impl.clj
index 80509cfefbc..800f550261d 100644
--- a/src/metabase/query_permissions/impl.clj
+++ b/src/metabase/query_permissions/impl.clj
@@ -45,7 +45,8 @@
(merge {:type qp.error-type/missing-required-permissions
:required-permissions required-perms
:actual-permissions (perms/permissions-for-user api/*current-user-id*)
- :permissions-error? true}
+ :permissions-error? true
+ :response/keys #{:required-permissions}}
additional-ex-data))))
;;; ---------------------------------------------- Permissions Checking ----------------------------------------------
diff --git a/src/metabase/query_processor/card.clj b/src/metabase/query_processor/card.clj
index 3c82e32b509..1e4c94937bd 100644
--- a/src/metabase/query_processor/card.clj
+++ b/src/metabase/query_processor/card.clj
@@ -283,7 +283,8 @@
(pr-str parameter-name))
{:type qp.error-type/invalid-parameter
:invalid-parameter request-parameter
- :allowed-parameters (keys template-tags)})))]
+ :allowed-parameters (keys template-tags)
+ :response/keys #{:invalid-parameter :allowed-parameters}})))]
;; now make sure the type agrees as well
(check-allowed-parameter-value-type parameter-name matching-widget-type (:type request-parameter)))))))
diff --git a/src/metabase/server/middleware/exceptions.clj b/src/metabase/server/middleware/exceptions.clj
index 6bc22fc0f31..b62cb708915 100644
--- a/src/metabase/server/middleware/exceptions.clj
+++ b/src/metabase/server/middleware/exceptions.clj
@@ -8,6 +8,7 @@
[metabase.server.middleware.security :as mw.security]
[metabase.server.settings :as server.settings]
[metabase.util :as u]
+ [metabase.util.api-error :as api-error]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log])
(:import
@@ -35,37 +36,38 @@
(defmethod api-exception-response Throwable
[^Throwable e request]
(let [{:keys [status-code], :as info} (ex-data e)
- other-info (dissoc info :status-code :schema :type :toucan2/context-trace ::log/context)
+ ;; only the keys the throw site listed go to the client; the rest is server-side context. See
+ ;; [[metabase.util.api-error]]
+ api-data (api-error/response-data info)
body (cond
- (and status-code (not= status-code 500) (empty? other-info))
- ;; If status code was specified (but not a 500 -- an unexpected error, and
- ;; other data wasn't, it's something like a 404. Return message as
- ;; the (plain-text) body.
+ (and status-code (not= status-code 500) (empty? api-data))
+ ;; If status code was specified (but not a 500 -- an unexpected error), and
+ ;; there is nothing client-facing in the ex-data, it's something like a 404.
+ ;; Return message as the (plain-text) body.
(.getMessage e)
;; if the response includes `:errors`, (e.g., it's something like a generic
- ;; parameter validation exception), just return the `other-info` from the
- ;; ex-data.
- (and status-code (:errors other-info))
- other-info
+ ;; parameter validation exception), just return the client-facing data.
+ (and status-code (:errors api-data))
+ api-data
;; a machine-readable error code means the throw site authored this as an
- ;; API response; return it as-is, without a stacktrace
- (and status-code (not= status-code 500) (:error-code other-info))
- (merge {:message (ex-message e)} other-info)
+ ;; API response; return it without a stacktrace
+ (and status-code (not= status-code 500) (:error-code api-data))
+ (merge {:message (ex-message e)} api-data)
;; allow administrators to configure their instances to suppress stacktraces
;; returns 500 with a generic message
(server.settings/hide-stacktraces)
{:message (tru "Something went wrong")}
- ;; Otherwise return the full `Throwable->map` representation with Stacktrace
- ;; and ex-data
+ ;; Otherwise return the `Throwable->map` representation with Stacktrace
+ ;; and the client-facing ex-data
:else
(merge
- (Throwable->map e)
+ (api-error/throwable->map e)
{:message (.getMessage e)}
- other-info))]
+ api-data))]
(when (nil? status-code)
(analytics/inc! :metabase-api/unhandled-errors))
{:status (or status-code 500)
diff --git a/src/metabase/server/streaming_response.clj b/src/metabase/server/streaming_response.clj
index 5e11bcf8d73..b91f1926c78 100644
--- a/src/metabase/server/streaming_response.clj
+++ b/src/metabase/server/streaming_response.clj
@@ -8,6 +8,7 @@
[metabase.server.settings :as server.settings]
[metabase.server.streaming-response.thread-pool :as thread-pool]
[metabase.util :as u]
+ [metabase.util.api-error :as api-error]
[metabase.util.async :as async.u]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -41,9 +42,9 @@
(.write os ba offset len)))
(defn- format-exception [e]
- (cond-> (Throwable->map e)
- ;; `:data` is the ex-data, which for QP exceptions routinely carries the whole query; drop it along with the
- ;; stacktrace and cause chain, as the (non-streaming) exception middleware does.
+ (cond-> (api-error/throwable->map e)
+ ;; `:data` is the client-facing part of the ex-data; drop it along with the stacktrace and cause chain, as the
+ ;; (non-streaming) exception middleware does.
(server.settings/hide-stacktraces) (dissoc :via :trace :data)))
;; Implemented by the output stream handed to a streaming response body, so that [[write-error!]] -- called from the
diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.clj
index 54c45ea21a3..b26b5531289 100644
--- a/src/metabase/session/api.clj
+++ b/src/metabase/session/api.clj
@@ -274,9 +274,10 @@
(if throttling-disabled?
(do-login)
(http-401-on-error
- (throttle/with-throttling [(login-throttlers :ip-address) ip-address
- (login-throttlers :username) (u/lower-case-en username)]
- (do-login))))))
+ ;; the last pair is checked first: by IP address, then by username
+ (call-with-failure-throttling [[(login-throttlers :username) (u/lower-case-en username)]
+ [(login-throttlers :ip-address) ip-address]]
+ do-login)))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
@@ -536,10 +537,8 @@
{:status-code 401
:errors {:_error (or (:error login-result) "Authentication failed")}})))))]
(http-401-on-error
- (if throttling-disabled?
- (do-login)
- (throttle/with-throttling [(login-throttlers :ip-address) (request/ip-address request)]
- (do-login))))))
+ (call-with-failure-throttling [[(login-throttlers :ip-address) (request/ip-address request)]]
+ do-login))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/settings/models/setting.clj b/src/metabase/settings/models/setting.clj
index 30c18eaa451..3bea2cea278 100644
--- a/src/metabase/settings/models/setting.clj
+++ b/src/metabase/settings/models/setting.clj
@@ -1046,10 +1046,11 @@
s-name (setting-name setting)]
(when (and feature (not (has-feature? feature)))
(throw (ex-info (tru "Setting {0} is not enabled because feature {1} is not available" s-name feature)
- {:status-code 402
- :status "error-premium-feature-not-available"
- :setting s-name
- :feature feature})))
+ {:status-code 402
+ :status "error-premium-feature-not-available"
+ :setting s-name
+ :feature feature
+ :response/keys #{:status}})))
(when (and enabled? (not (enabled?)))
(throw (ex-info (tru "Setting {0} is not enabled" s-name)
{:status-code 400
diff --git a/src/metabase/tiles/api.clj b/src/metabase/tiles/api.clj
index f1beba6f89a..5fd5a79f447 100644
--- a/src/metabase/tiles/api.clj
+++ b/src/metabase/tiles/api.clj
@@ -172,7 +172,8 @@
[{{:keys [rows cols]} :data, :as qp-response} lat-field-ref lon-field-ref]
(when-not (= (:status qp-response) :completed)
(throw (ex-info (format "Error running tiles query: %s" (:error qp-response))
- (assoc qp-response :status-code 400))))
+ ;; `:error` is client-facing by default, and the message already carries it
+ (-> qp-response (dissoc :error) (assoc :status-code 400)))))
(let [lat-id-or-name (second lat-field-ref)
lon-id-or-name (second lon-field-ref)
diff --git a/src/metabase/util/api_error.clj b/src/metabase/util/api_error.clj
new file mode 100644
index 00000000000..d6d73225177
--- /dev/null
+++ b/src/metabase/util/api_error.clj
@@ -0,0 +1,59 @@
+(ns metabase.util.api-error
+ "Which parts of an exception's `ex-data` an API error response may send to the client.
+
+ The API error handling ([[metabase.server.middleware.exceptions]], [[metabase.server.streaming-response]]) sends only
+ client-facing keys of the ex-data. Everything else is server-side context (queries, ids, permissions) that stays out
+ of the response, so each client-facing key is opted in rather than secrets being opted out. Keys keep their names, so
+ code reading the ex-data is unaffected by what is sent.
+
+ ## Keys always sent
+
+ These are idiomatically sent whenever they are present, without being listed (see [[default-response-keys]]):
+
+ - `:message`, `:error_message` a human-readable message, sent in place of the exception's own message
+ - `:error` a human-readable message
+ - `:errors` validation errors, usually field name -> message, with `:_error` for the whole form
+ - `:error-code`, `:error_code` a machine-readable error code; with a non-500 status the response has no stacktrace
+
+ `:status-code` is not sent as a key: it becomes the response's HTTP status.
+
+ ## Sending other keys
+
+ List them under `:response/keys`:
+
+ (throw (ex-info (tru \"Invalid {0}\" label) {:status-code 400, :field key, :card-id id, :response/keys #{:field}}))
+
+ responds with `{:field ...}`, keeping `:card-id` server-side. When the data comes from elsewhere, like ex-data being
+ rethrown, use [[extend-response-keys]], which adds to the keys already listed instead of replacing them.")
+
+(defn extend-response-keys
+ "Add `ks` to the `:response/keys` of `data`, the keys that are sent to the client, keeping any already listed. For
+ data built elsewhere, like ex-data being rethrown; with a map literal, put `:response/keys` in it instead.
+
+ (throw (ex-info (ex-message e) (merge {:status-code 400} (api-error/extend-response-keys (ex-data e) :details)) e))"
+ [data & ks]
+ (cond-> data
+ (seq ks) (update :response/keys (fnil into #{}) ks)))
+
+(def ^:private default-response-keys
+ "Keys sent to the client whenever they are present in ex-data, without being listed under `:response/keys`."
+ #{:message :error_message :error :errors :error-code :error_code})
+
+(defn response-data
+ "The client-facing part of an exception's `data`: the entries for its listed keys and [[default-response-keys]]."
+ [data]
+ (select-keys data (into default-response-keys (:response/keys data))))
+
+(defn throwable->map
+ "[[clojure.core/Throwable->map]] with each `:data` (the root cause's, and every `:via` entry's) reduced to its
+ [[response-data]] and `:status-code`, dropping it when there is neither."
+ [^Throwable e]
+ (let [filter-data (fn [x]
+ (let [data (merge (response-data (:data x))
+ (select-keys (:data x) [:status-code]))]
+ (if (seq data)
+ (assoc x :data data)
+ (dissoc x :data))))]
+ (-> (Throwable->map e)
+ filter-data
+ (update :via #(mapv filter-data %)))))
diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.clj
index 169e5a18b81..6f6b4c5fb92 100644
--- a/src/metabase/warehouse_schema/models/table.clj
+++ b/src/metabase/warehouse_schema/models/table.clj
@@ -114,9 +114,10 @@
(let [kw (keyword value)]
(when-not (contains? writable-data-authority-types kw)
(throw (ex-info (str "Illegal value for data_authority: " kw)
- {:field :data_authority
- :value value
- :status-code 400})))
+ {:field :data_authority
+ :value value
+ :status-code 400
+ :response/keys #{:field}})))
(name kw))))})
(def legacy-data-layer->current
diff --git a/src/metabase/warehouse_schema_rest/api/field.clj b/src/metabase/warehouse_schema_rest/api/field.clj
index d9a93e76df1..cfab0448a90 100644
--- a/src/metabase/warehouse_schema_rest/api/field.clj
+++ b/src/metabase/warehouse_schema_rest/api/field.clj
@@ -182,7 +182,8 @@
{:status-code 400
:base-type (:base_type field)
:coercion-strategy coercion-strategy
- :effective-type effective}))))))
+ :effective-type effective
+ :response/keys #{:base-type :coercion-strategy :effective-type}}))))))
removed-fk? (removed-fk-semantic-type? (:semantic_type field) new-semantic-type)
fk-target-field-id (get body :fk_target_field_id (:fk_target_field_id field))]
;; validate that fk_target_field_id is a valid Field in the same database
diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.clj
index 96ed6f5251a..17ce8317c9d 100644
--- a/test/metabase/actions_rest/api_test.clj
+++ b/test/metabase/actions_rest/api_test.clj
@@ -193,22 +193,20 @@
(let [action (cross-db-action (:id model) test-data-id)
response (mt/user-http-request :rasta :post 400 "action" action)]
(testing "Checks both databases for actions enabled"
- (is (partial= {:message "Actions are not enabled."
- :data {:database-id test-data-id}}
- response))))))))))
+ (is (= "Actions are not enabled."
+ response))))))))))
(testing "When executing, both dbs are checked for enabled"
(mt/dataset test-data
(let [test-data-id (mt/id)]
(mt/with-actions-test-data-and-actions-enabled
(mt/with-actions [{model-id :id} {:type :model, :dataset_query (mt/mbql-query categories)}
{action-on-other-id :action-id} (cross-db-action model-id test-data-id)]
- (is (partial= {:message "Actions are not enabled."
- :data {:database-id test-data-id}}
- (mt/user-http-request :rasta
- :post 400
- (format "action/%s/execute" action-on-other-id)
- ;; Twitter is the current value so effectively a no-op
- {:parameters {:id 1 :source "Twitter"}})))))))
+ (is (= "Actions are not enabled."
+ (mt/user-http-request :rasta
+ :post 400
+ (format "action/%s/execute" action-on-other-id)
+ ;; Twitter is the current value so effectively a no-op
+ {:parameters {:id 1 :source "Twitter"}})))))))
(testing "When actions are enabled on the other database"
(mt/dataset test-data
(let [test-data-id (mt/id)]
@@ -250,7 +248,7 @@
:parameters []}]
(testing "creating it is refused because actions are disabled on the query's real DB"
(is (= "Actions are not enabled."
- (:cause (mt/user-http-request :crowberto :post 400 "action" action))))))))))))))
+ (mt/user-http-request :crowberto :post 400 "action" action)))))))))))))
(deftest unified-action-create-test
(mt/test-helpers-set-global-values!
@@ -295,8 +293,7 @@
(testing "actions disabled"
(mt/with-actions-disabled
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto :post 400 "action" initial-action))))))
+ (mt/user-http-request :crowberto :post 400 "action" initial-action)))))
(testing "an implicit action on a plain card instead of a model"
(mt/with-temp [:model/Card {plain-card-id :id} {:dataset_query (mt/mbql-query users)}]
(is (= "Actions must be made with models, not cards."
@@ -319,8 +316,7 @@
(testing "actions disabled"
(mt/with-actions-disabled
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto :put 400 action-path (update-fn {}))))))))
+ (mt/user-http-request :crowberto :put 400 action-path (update-fn {})))))))
(testing "Get"
(is (partial= (expected-fn updated-action)
(mt/user-http-request :crowberto :get 200 action-path)))
@@ -703,8 +699,8 @@
(mt/with-actions-disabled
(testing "changing the query is refused"
(is (= "Actions are not enabled."
- (:cause (mt/user-http-request :crowberto :put 400 path
- {:dataset_query (:dataset_query created)})))))
+ (mt/user-http-request :crowberto :put 400 path
+ {:dataset_query (:dataset_query created)}))))
(testing "renaming, settings and archiving are allowed"
(is (=? {:name "Renamed"}
(mt/user-http-request :crowberto :put 200 path {:name "Renamed"})))
@@ -816,8 +812,7 @@
(testing "We *cannot* share an action if actions are disabled"
(mt/with-actions-disabled
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto :post 400 (format "action/%d/public_link" action-id)))))))
+ (mt/user-http-request :crowberto :post 400 (format "action/%d/public_link" action-id))))))
(testing "We get a 404 if the Action doesn't exist"
(is (= "Not found."
(mt/user-http-request :crowberto :post 404 (format "action/%d/public_link" Integer/MAX_VALUE)))))))
@@ -914,11 +909,10 @@
(testing "Check that we get a 400 if actions are disabled for the database."
(mt/with-temp-vals-in-db :model/Database (mt/id) {:settings {:database-enable-actions false}}
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto
- :post 400
- (format "action/%s/execute" action-id)
- {:parameters {:id 1 :name "European"}})))))))))
+ (mt/user-http-request :crowberto
+ :post 400
+ (format "action/%s/execute" action-id)
+ {:parameters {:id 1 :name "European"}}))))))))
(deftest execute-action-permission-test
(mt/test-drivers (mt/normal-drivers-with-feature :actions)
@@ -1045,7 +1039,7 @@
(mt/with-actions-disabled
(testing "error if actions is disabled"
(is (= "Actions are not enabled."
- (:message (mt/user-http-request :crowberto :post 400 (format "action/%d/execute/values" delete-action-id) {:parameters {"id" 1}}))))))))))
+ (mt/user-http-request :crowberto :post 400 (format "action/%d/execute/values" delete-action-id) {:parameters {"id" 1}})))))))))
;; This is just to test the flow, a comprehensive tests for error type ares in
;; [[metabase.driver.sql-jdbc.actions-test/action-error-handling-test]]
diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.clj
index cf35f324a82..f5025a237b9 100644
--- a/test/metabase/agent_api/api_test.clj
+++ b/test/metabase/agent_api/api_test.clj
@@ -729,6 +729,18 @@
:query (:query construct-resp)
:collection_id locked-id}))))))
+(deftest create-question-nested-unreadable-card-403-does-not-leak-definition-test
+ (testing "The 403 for a query nesting a Card the caller cannot read does not echo that Card's definition"
+ (mt/with-temp [:model/Card {secret-id :id} {:collection_id (:id (collection/user->personal-collection
+ (mt/user->id :crowberto)))
+ :dataset_query (mt/native-query {:query "SELECT 1 AS sec_1173_marker"})}]
+ (let [q {:database (mt/id) :type :query :query {:source-table (str "card__" secret-id)}}
+ body (mt/user-http-request :rasta :post 403 "agent/v1/question"
+ {:name "Should Not Save"
+ :query (u/encode-base64 (json/encode q))})]
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ body))))))
+
;;; ----------------------------------------- Construct / Save Native Query ------------------------------------------
(deftest construct-native-query-test
@@ -1469,9 +1481,9 @@
:visualization_settings
{:timeline.selected_timeline_ids [(:id timeline)]}}]
(perms/revoke-collection-permissions! (perms-group/all-users) restricted)
- (is (= "You don't have permissions to do that."
- (:cause (mt/user-http-request :rasta :put 403 (str "agent/v1/dashboard/" dash-id)
- {:dashcards [{:action "add" :card_id card-id}]}))))
+ (is (re-find #"You don't have permissions to do that\."
+ (mt/user-http-request :rasta :put 403 (str "agent/v1/dashboard/" dash-id)
+ {:dashcards [{:action "add" :card_id card-id}]})))
(is (empty? (t2/select :model/DashboardCard :dashboard_id dash-id)))
(testing "a user who can read the timeline can add it"
(mt/user-http-request :crowberto :put 200 (str "agent/v1/dashboard/" dash-id)
diff --git a/test/metabase/api/common_test.clj b/test/metabase/api/common_test.clj
index 50f1bcc2611..3876afcc127 100644
--- a/test/metabase/api/common_test.clj
+++ b/test/metabase/api/common_test.clj
@@ -88,6 +88,20 @@
identity
(fn [e] (throw e)))))))
+(deftest ^:parallel check-map-message-is-client-facing-test
+ (testing "a map message is the response body, and its keys stay readable in the ex-data"
+ (let [e (try
+ (api/check false [400 {:message "Nope", :error_code "archived", :errors {:id "bad"}}])
+ (catch ExceptionInfo e e))]
+ (is (=? {:status-code 400, :error_code "archived", :errors {:id "bad"}}
+ (ex-data e)))
+ (is (= {:message "Nope", :error_code "archived", :errors {:id "bad"}}
+ (:body (mock-api-fn (fn [_] (throw e)))))))))
+
+(deftest ^:parallel checkp-errors-are-client-facing-test
+ (is (= {:errors {:name "is bad"}}
+ (:body (mock-api-fn (fn [_] (api/checkp false "name" "is bad")))))))
+
(methodical/defmethod hawk.approx/=?-diff [java.util.regex.Pattern clojure.lang.Symbol]
[expected-re sym]
(hawk.approx/=?-diff expected-re (name sym)))
diff --git a/test/metabase/channel/impl/http_test.clj b/test/metabase/channel/impl/http_test.clj
index a68e0b57590..7616ebdd4a6 100644
--- a/test/metabase/channel/impl/http_test.clj
+++ b/test/metabase/channel/impl/http_test.clj
@@ -13,6 +13,7 @@
[metabase.server.handler :as server.handler]
[metabase.server.middleware.json :as mw.json]
[metabase.test :as mt]
+ [metabase.util.api-error :as api-error]
[metabase.util.i18n :refer [deferred-tru]]
[metabase.util.malli :as mu]
[ring.adapter.jetty :as jetty]
@@ -148,11 +149,12 @@
(channel/can-connect? :channel/http details))
(defmacro exception-data
+ "The client-facing ex-data of the exception `body` throws."
[& body]
`(try
~@body
(catch Exception e#
- (ex-data e#))))
+ (api-error/response-data (ex-data e#)))))
(deftest can-connect-no-auth-test
(mt/with-temp-env-var-value! [mb-http-channel-allowed-networks "allow-all"]
diff --git a/test/metabase/channel/rest/api/channel_test.clj b/test/metabase/channel/rest/api/channel_test.clj
index 155d86ff53c..50b4dadef50 100644
--- a/test/metabase/channel/rest/api/channel_test.clj
+++ b/test/metabase/channel/rest/api/channel_test.clj
@@ -148,7 +148,7 @@
(mt/user-http-request :crowberto :post 400 "channel/test"
(assoc default-test-channel :details {:return-type "return-value"
:return-value false})))))
- (testing "return the exception message and data if the channel throws an exception"
+ (testing "return the exception message and client-facing data if the channel throws an exception"
(is (= {:message "Test error"
:data {:errors {:email "Invalid email"}}}
(mt/user-http-request :crowberto :post 400 "channel/test"
diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.clj
index 7c80cafb6af..fbdfa795a97 100644
--- a/test/metabase/dashboards_rest/api_test.clj
+++ b/test/metabase/dashboards_rest/api_test.clj
@@ -4538,9 +4538,8 @@
dashcard-id)]
(testing "Without actions enabled"
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto :post 400 execute-path
- {:parameters {"name" "Birds"}})))))
+ (mt/user-http-request :crowberto :post 400 execute-path
+ {:parameters {"name" "Birds"}}))))
;; Actions cannot run with access to the DB blocked, which is an enterprise feature. See tests in
;; enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj and at the bottom of
;; this file
@@ -4577,9 +4576,8 @@
dashcard-id)]
(testing "Fails with actions disabled"
(is (= "Actions are not enabled."
- (:cause
- (mt/user-http-request :crowberto :post 400 execute-path
- {:parameters {"id" 1}})))))
+ (mt/user-http-request :crowberto :post 400 execute-path
+ {:parameters {"id" 1}}))))
;; Actions cannot run with access to the DB blocked, which is an enterprise feature. See tests in
;; enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj and at the bottom of
;; this file.
diff --git a/test/metabase/indexed_entities/api_test.clj b/test/metabase/indexed_entities/api_test.clj
index af0dbcb1572..692877d1e96 100644
--- a/test/metabase/indexed_entities/api_test.clj
+++ b/test/metabase/indexed_entities/api_test.clj
@@ -90,8 +90,7 @@
{:model_id (:id model)
:pk_ref (by-name "id")
:value_ref not-in-query})]
- (is (=? {:cause #"Could not identify field by ref.*"}
- response)))))))))
+ (is (re-find #"Could not identify field by ref.*" response)))))))))
(deftest snowplow-create-model-index-event-test
(testing "Send a snowplow event when “Surface individual records matching against column” is toggled on (and saved)"
diff --git a/test/metabase/llm/api/provider_test.clj b/test/metabase/llm/api/provider_test.clj
index 96b74b2e150..7ef947ba363 100644
--- a/test/metabase/llm/api/provider_test.clj
+++ b/test/metabase/llm/api/provider_test.clj
@@ -384,7 +384,7 @@
(throw (ex-info "The vLLM server answered with text instead of calling a tool."
{:api-error true :status-code 400})))]
(mt/with-temporary-setting-values [llm-providers []]
- (is (=? {:message "The vLLM server answered with text instead of calling a tool."}
+ (is (=? "The vLLM server answered with text instead of calling a tool."
(mt/user-http-request :crowberto :post 400 "llm/providers"
{:type "vllm"
:config {:base-url "http://vllm.internal:8000/v1"}})))
@@ -397,9 +397,9 @@
(mt/with-temporary-setting-values [llm-providers []]
(is (= (str "Could not reach the vLLM server at http://vllm.internal:8000/v1. "
"Check that it is running and that the base URL is correct.")
- (:message (mt/user-http-request :crowberto :post 400 "llm/providers"
- {:type "vllm"
- :config {:base-url "http://vllm.internal:8000/v1"}}))))
+ (mt/user-http-request :crowberto :post 400 "llm/providers"
+ {:type "vllm"
+ :config {:base-url "http://vllm.internal:8000/v1"}})))
(is (= [] (llm.provider/connections)))))))
(deftest create-openai-compatible-connection-test
@@ -434,8 +434,8 @@
(mt/with-dynamic-fn-redefs [http/request (fn [_] {:status 200 :body {:object "list"}})]
(mt/with-temporary-setting-values [llm-providers []]
(is (= "Anthropic returned an unexpected model list response"
- (:message (mt/user-http-request :crowberto :post 400 "llm/providers"
- {:type "anthropic" :config {:api-key "sk-ant-nope"}}))))
+ (mt/user-http-request :crowberto :post 400 "llm/providers"
+ {:type "anthropic" :config {:api-key "sk-ant-nope"}})))
(is (= [] (llm.provider/connections)))))))
(deftest a-refused-listing-logs-only-a-malformed-catalog-test
@@ -604,8 +604,8 @@
(mt/with-temporary-setting-values [llm-providers []]
(let [connect! (fn [messages]
(mt/with-dynamic-fn-redefs [http/request (fn [_] (bedrock-test/runtime-response-for messages))]
- (:message (mt/user-http-request :crowberto :post 400 "llm/providers"
- bedrock-inference-profile-connection))))
+ (mt/user-http-request :crowberto :post 400 "llm/providers"
+ bedrock-inference-profile-connection)))
incomplete "AWS Bedrock returned an incomplete response from \"eu.anthropic.claude-sonnet-4-6\""]
(are [messages error] (= error (connect! messages))
[bedrock-test/message-start bedrock-test/stream-error] "Model stream error"
@@ -647,7 +647,7 @@
(deftest create-does-not-save-when-credentials-are-rejected-test
(mt/with-temporary-setting-values [llm-providers []]
(mt/with-dynamic-fn-redefs [metabot.self/list-models (rejected-credentials "Anthropic API key expired or invalid")]
- (is (=? {:message "Anthropic API key expired or invalid"}
+ (is (=? "Anthropic API key expired or invalid"
(mt/user-http-request :crowberto :post 400 "llm/providers"
{:type "anthropic" :config {:api-key "sk-ant-nope"}})))
(is (= [] (llm.provider/connections))))))
@@ -1085,7 +1085,7 @@
(deftest update-does-not-save-when-credentials-are-rejected-test
(mt/with-temporary-setting-values [llm-providers [(connection "anthropic" "anthropic" {:api-key "sk-ant-stored"})]]
(mt/with-dynamic-fn-redefs [metabot.self/list-models (rejected-credentials "Anthropic API key expired or invalid")]
- (is (=? {:message "Anthropic API key expired or invalid"}
+ (is (=? "Anthropic API key expired or invalid"
(mt/user-http-request :crowberto :put 400 "llm/providers/anthropic"
{:config {:api-key "sk-ant-rotated"}})))
(is (= {:api-key "sk-ant-stored"} (stored-config "anthropic"))))))
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 0085655f80a..7fff1c3eb0d 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -812,7 +812,7 @@
(mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_] (swap! llm-calls inc) (mut/mock-llm-response []))
conversation-title/ensure-title! (fn [& _] (swap! title-calls inc) {:status :ready :title "x"})]
(mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
- (is (=? {:message #"Unknown profile"}
+ (is (=? #"Unknown profile.*"
(mt/user-http-request :rasta :post 400 "metabot/agent-streaming"
{:message "hello"
:context {}
diff --git a/test/metabase/metrics/api_dimension_test.clj b/test/metabase/metrics/api_dimension_test.clj
index b0328afde08..44611124f66 100644
--- a/test/metabase/metrics/api_dimension_test.clj
+++ b/test/metabase/metrics/api_dimension_test.clj
@@ -81,7 +81,7 @@
(metrics/sync-dimensions! :metadata/metric (:id metric))
(let [response (mt/user-http-request :rasta :get 400
(str "metric/" (:id metric) "/dimension/" fake-dimension-id "/values"))]
- (is (re-find #"Dimension not found" (:message response)))))))
+ (is (re-find #"Dimension not found" response))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/metric/:id/dimension/:key/search/:query |
@@ -121,7 +121,7 @@
(let [response (mt/user-http-request :rasta :get 400
(str "metric/" (:id metric) "/dimension/" fake-dimension-id "/search")
:query "test")]
- (is (re-find #"Dimension not found" (:message response)))))))
+ (is (re-find #"Dimension not found" response))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/metric/:id/dimension/:key/remapping |
@@ -161,7 +161,7 @@
(let [response (mt/user-http-request :rasta :get 400
(str "metric/" (:id metric) "/dimension/" fake-dimension-id "/remapping")
:value "1")]
- (is (re-find #"Dimension not found" (:message response)))))))
+ (is (re-find #"Dimension not found" response))))))
(deftest dimension-remapping-requires-value-param-test
(testing "GET /api/metric/:id/dimension/:key/remapping requires value parameter"
diff --git a/test/metabase/notification/test_util.clj b/test/metabase/notification/test_util.clj
index 965ccadab5f..a05f4a0cb55 100644
--- a/test/metabase/notification/test_util.clj
+++ b/test/metabase/notification/test_util.clj
@@ -31,7 +31,7 @@
[_channel-type {:keys [return-type return-value] :as _details}]
(case return-type
"throw"
- (throw (ex-info "Test error" return-value))
+ (throw (ex-info "Test error" (assoc return-value :response/keys (set (keys return-value)))))
"return-value"
return-value))
diff --git a/test/metabase/parameters/params_test.clj b/test/metabase/parameters/params_test.clj
index d15a09aee88..de7f8e43b28 100644
--- a/test/metabase/parameters/params_test.clj
+++ b/test/metabase/parameters/params_test.clj
@@ -299,3 +299,14 @@
(t2/with-call-count [call-count]
(params/dashcards->param-field-ids dashcards)
(call-count)))))))))))
+
+(deftest ^:parallel invalid-parameters-errors-are-humanized-test
+ (testing "`:errors` are client-facing, so they are humanized messages rather than Malli explanations"
+ (doseq [[thunk desc] [[#(params/assert-valid-parameters {:parameters [{:id 1}]})
+ "parameters"]
+ [#(params/assert-valid-parameter-mappings {:parameter_mappings [{:card_id "x"}]})
+ "parameter mappings"]]]
+ (testing desc
+ (let [errors (:errors (try (thunk) (catch clojure.lang.ExceptionInfo e (ex-data e))))]
+ (is (some? errors))
+ (is (not-any? #(and (map? %) (contains? % :schema)) (tree-seq coll? seq errors))))))))
diff --git a/test/metabase/premium_features/token_check_test.clj b/test/metabase/premium_features/token_check_test.clj
index a9b361c7fda..43b048d0760 100644
--- a/test/metabase/premium_features/token_check_test.clj
+++ b/test/metabase/premium_features/token_check_test.clj
@@ -15,6 +15,7 @@
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
+ [metabase.util.api-error :as api-error]
[metabase.util.json :as json]
[metabase.util.malli.registry :as mr]
[methodical.core :as methodical]
@@ -1096,3 +1097,12 @@
(is (= token (premium-features/premium-embedding-token))))
(finally
(token-check/clear-cache!)))))))
+
+(deftest invalid-token-error-response-test
+ (testing "an invalid token's error response carries its `:error-details`, and nothing else from the ex-data"
+ (let [data (try (token-check/-set-premium-embedding-token! "not-a-token")
+ (catch clojure.lang.ExceptionInfo e (ex-data e)))]
+ (is (= {:message "Token format is invalid."
+ :error-details "Token should be 64 hexadecimal characters."}
+ (api-error/response-data data)))
+ (is (= 400 (:status-code data))))))
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index fe47edef0bd..50523328cea 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -31,7 +31,6 @@
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
- [metabase.permissions.util :as perms.u]
[metabase.queries-rest.api.card :as api.card]
[metabase.queries.card :as queries.card]
[metabase.queries.models.card.metadata :as card.metadata]
@@ -645,7 +644,7 @@
[:model/Card {card-id :id} {:name "Card"
:display "table"}]
(is (= "Card with type table is not compatible to have series"
- (:message (mt/user-http-request :crowberto :get 400 (format "card/%d/series" card-id)))))))
+ (mt/user-http-request :crowberto :get 400 (format "card/%d/series" card-id))))))
(testing "404 if the card does not exsits"
(is (= "Not found."
(mt/user-http-request :crowberto :get 404 (format "card/%d/series" Integer/MAX_VALUE))))))
@@ -1584,19 +1583,24 @@
(testing "admin should be able to save a Card if All Users doesn't have ad-hoc data perms"
(is (some? (create-card! :crowberto 200))))
(testing "non-admin should get an error"
- (testing "Permissions errors should be meaningful and include info for debugging (#14931)"
- (is (malli= [:map
- [:message [:= "You cannot save this Question because you do not have permissions to run its query."]]
- [:query [:map
- [:lib/type [:= "mbql/query"]]
- [:stages [:sequential
- {:min 1, :max 1}
- [:map
- [:source-table [:= (mt/id :venues)]]]]]]]
- [:required-perms :map]
- [:actual-perms [:sequential perms.u/PathSchema]]
- [:trace [:sequential :any]]]
- (create-card! :rasta 403))))))))))
+ (testing "Permissions errors keep their meaningful message (#14931)"
+ (testing "but not the ex-data: the (preprocessed) query inlines source Cards the user may not read (SEC-1173)"
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ (create-card! :rasta 403)))))))))))
+
+(deftest create-card-nested-unreadable-card-403-does-not-leak-definition-test
+ (testing "POST /api/card"
+ (testing "the 403 for a query nesting a Card the caller cannot read does not echo that Card's definition"
+ (mt/with-temp [:model/Card {secret-id :id} {:collection_id (u/the-id (collection/user->personal-collection
+ (mt/user->id :crowberto)))
+ :dataset_query (mt/native-query {:query "SELECT 1 AS sec_1173_marker"})}]
+ (let [body (mt/with-model-cleanup [:model/Card]
+ (mt/user-http-request :rasta :post 403 "card"
+ (merge (mt/with-temp-defaults :model/Card)
+ {:dataset_query (mt/mbql-query nil {:source-table (str "card__" secret-id)})
+ :collection_id (-> :rasta mt/user->id collection/user->personal-collection u/the-id)})))]
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ body)))))))
(deftest create-card-parameter-permissions-generic-error-test
(testing "POST /api/card"
@@ -2310,18 +2314,10 @@
:name "Updated name"}
(update-card! :rasta 200 {:name "Updated name"}))))
(testing "should *not* be allowed to update query"
- (testing "Permissions errors should be meaningful and include info for debugging (#14931)"
- (is (malli= [:map
- [:message [:= "You cannot save this Question because you do not have permissions to run its query."]]
- [:query [:map
- [:stages [:sequential
- {:min 1, :max 1}
- [:map
- [:source-table [:= (mt/id :users)]]]]]]]
- [:required-perms :map]
- [:actual-perms [:sequential perms.u/PathSchema]]
- [:trace [:sequential :any]]]
- (update-card! :rasta 403 {:dataset_query (mt/mbql-query users)}))))
+ (testing "Permissions errors keep their meaningful message (#14931)"
+ (testing "but not the ex-data: the (preprocessed) query inlines source Cards the user may not read (SEC-1173)"
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ (update-card! :rasta 403 {:dataset_query (mt/mbql-query users)})))))
(testing "make sure query hasn't changed in the DB"
(is (=? {:lib/type :mbql/query
:stages [{:source-table (mt/id :checkins)}]}
@@ -4420,7 +4416,7 @@
:name "Bad Card"
:display "table"
:visualization_settings {}}]
- (is (=? {:message #"Invalid Field Filter: Field \d+ \"VENUES\"\.\"NAME\" belongs to Database \d+ \"test-data \(h2\)\", but the query is against Database \d+ \"daily-bird-counts \(h2\)\""}
+ (is (=? #"Invalid Field Filter: Field \d+ \"VENUES\"\.\"NAME\" belongs to Database \d+ \"test-data \(h2\)\", but the query is against Database \d+ \"daily-bird-counts \(h2\)\".*"
(mt/user-http-request :crowberto :post 400 "card" card-data)))))))
(deftest ^:parallel format-export-middleware-test
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index e01b6c7ebef..262ea7a8560 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -667,8 +667,7 @@
(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data :unrestricted)
(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/create-queries :query-builder)
(is (malli= [:map
- [:permissions-error? [:= true]]
- [:message [:= "You do not have permissions to run this query."]]]
+ [:message [:= "You do not have permissions to run this query."]]]
(mt/user-http-request :rasta :post "dataset/native"
(mt/mbql-query venues
{:fields [$id $name]}))))))))))
diff --git a/test/metabase/query_processor/nested_queries_test.clj b/test/metabase/query_processor/nested_queries_test.clj
index 1bb830d4e61..58f14ab6e62 100644
--- a/test/metabase/query_processor/nested_queries_test.clj
+++ b/test/metabase/query_processor/nested_queries_test.clj
@@ -852,16 +852,16 @@
#_{:clj-kondo/ignore [:discouraged-var]}
(mt/with-temp [:model/Collection dest-card-collection]
(perms/grant-collection-readwrite-permissions! (perms/all-users-group) dest-card-collection)
- (is (=? {:message "You cannot save this Question because you do not have permissions to run its query."}
- (save-card-via-API-with-native-source-query! 403 (mt/db) nil dest-card-collection)))))
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ (save-card-via-API-with-native-source-query! 403 (mt/db) nil dest-card-collection)))))
(testing "Card in a different Collection for which we do not have perms"
;; allowing `with-temp` here since we need it to make Collections
#_{:clj-kondo/ignore [:discouraged-var]}
(mt/with-temp [:model/Collection source-card-collection {}
:model/Collection dest-card-collection {}]
(perms/grant-collection-readwrite-permissions! (perms/all-users-group) dest-card-collection)
- (is (=? {:message "You cannot save this Question because you do not have permissions to run its query."}
- (save-card-via-API-with-native-source-query! 403 (mt/db) source-card-collection dest-card-collection)))))
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ (save-card-via-API-with-native-source-query! 403 (mt/db) source-card-collection dest-card-collection)))))
(testing "similarly, if we don't have *write* perms for the dest collection it should also fail"
(testing "Try to save in the Root Collection"
;; allowing `with-temp` here since we need it to make Collections
diff --git a/test/metabase/server/middleware/exceptions_test.clj b/test/metabase/server/middleware/exceptions_test.clj
index 513e7e2e246..c96aa2804de 100644
--- a/test/metabase/server/middleware/exceptions_test.clj
+++ b/test/metabase/server/middleware/exceptions_test.clj
@@ -36,13 +36,33 @@
(is (vector? (get-in response [:body :trace]))
"Stacktrace should be a vector")))))
-(deftest api-exception-response-includes-ex-data-test
- (testing "When hide-stacktraces is false, exception response includes ex-data"
+(deftest api-exception-response-includes-only-exposed-ex-data-test
+ (testing "When hide-stacktraces is false, exception response includes the ex-data keys the throw site listed"
(mt/with-temporary-setting-values [server.settings/hide-stacktraces false]
- (let [exception (create-test-exception "Test error message")
- response (mw.exceptions/api-exception-response exception nil)]
- (is (= "test-value" (get-in response [:body :custom-data]))
- "Response should include custom data from ex-info")))))
+ (let [exception (ex-info "Test error message"
+ {:custom-data "secret", :shown "test-value", :response/keys #{:shown}}
+ (ex-info "cause" {:cause-data "secret", :cause-shown 1, :response/keys #{:cause-shown}}))
+ response (mw.exceptions/api-exception-response exception nil)]
+ (is (= "test-value" (get-in response [:body :shown])))
+ (testing "nothing unlisted is sent, anywhere in the body, nor the list itself"
+ (is (not (str/includes? (pr-str (:body response)) "secret")))
+ (is (not (str/includes? (pr-str (:body response)) "response/keys"))))))))
+
+(deftest api-exception-response-does-not-leak-ex-data-test
+ (testing "a 4xx whose ex-data carries server-side context (e.g. a preprocessed query) does not send it (SEC-1173)"
+ (doseq [hide? [false true]]
+ (mt/with-temporary-setting-values [server.settings/hide-stacktraces hide?]
+ (let [exception (ex-info "You cannot save this Question because you do not have permissions to run its query."
+ {:status-code 403
+ :query {:native "SELECT salary FROM payroll"}
+ :required-perms #{"/db/1/"}})
+ response (mw.exceptions/api-exception-response exception nil)
+ body (pr-str (:body response))]
+ (is (= 403 (:status response)))
+ (is (= "You cannot save this Question because you do not have permissions to run its query."
+ (:body response)))
+ (is (not (str/includes? body "SELECT salary")))
+ (is (not (str/includes? body "required-perms"))))))))
(deftest api-exception-response-includes-exception-chain-test
(testing "When hide-stacktraces is false, exception response includes exception chain information"
@@ -53,7 +73,8 @@
"Response should contain :via key with exception chain")))))
(deftest api-exception-response-error-code-test
- (testing "a non-500 that declares an :error-code returns its structured body without a stacktrace, whatever hide-stacktraces says"
+ (testing (str "a non-500 with an :error-code, client-facing without being listed, returns its structured body "
+ "without a stacktrace, whatever hide-stacktraces says")
(doseq [hide? [false true]]
(mt/with-temporary-setting-values [server.settings/hide-stacktraces hide?]
(let [exception (ex-info "You are out of tokens."
@@ -139,38 +160,40 @@
(is (= "Resource not found" (:body response))
"Should return plain message for 404s")))))
-(deftest api-exception-response-404-with-extra-data-hides-details-test
- (testing "404 errors with extra data hide details when hide-stacktraces is enabled"
- (mt/with-temporary-setting-values [server.settings/hide-stacktraces true]
- (let [exception (ex-info "Resource not found with details" {:status-code 404 :resource-id 123})
- response (mw.exceptions/api-exception-response exception nil)]
- (is (= 404 (:status response))
- "Status should remain 404 from exception")
- (is (= "Something went wrong" (get-in response [:body :message]))
- "Should return generic message")
- (is (not (contains? (:body response) :resource-id))
- "Should not include resource-id from ex-data")))))
+(deftest api-exception-response-404-with-internal-data-test
+ (testing "a non-500 whose ex-data has nothing client-facing returns its plain message, whatever hide-stacktraces says"
+ (doseq [hide? [false true]]
+ (mt/with-temporary-setting-values [server.settings/hide-stacktraces hide?]
+ (let [exception (ex-info "Resource not found with details" {:status-code 404 :resource-id 123})
+ response (mw.exceptions/api-exception-response exception nil)]
+ (is (= 404 (:status response))
+ "Status should remain 404 from exception")
+ (is (= "Resource not found with details" (:body response))
+ "Should return the message as the body, without the internal ex-data"))))))
(deftest api-exception-response-validation-errors-with-stacktraces-disabled-test
(testing "Validation errors with :errors key are returned when hide-stacktraces is false"
(mt/with-temporary-setting-values [server.settings/hide-stacktraces false]
(let [exception (ex-info "Validation failed"
{:status-code 400
- :errors {:email "Invalid email format"
+ :params {:password "hunter2"}
+ :errors {:email "Invalid email format"
:password "Password too short"}})
response (mw.exceptions/api-exception-response exception nil)]
(is (= 400 (:status response)))
(is (= {:email "Invalid email format"
:password "Password too short"}
(get-in response [:body :errors]))
- "Should include validation errors")))))
+ "Should include validation errors")
+ (is (not (contains? (:body response) :params)))))))
(deftest api-exception-response-validation-errors-with-stacktraces-enabled-test
(testing "Validation errors with :errors key are returned even when hide-stacktraces is true"
(mt/with-temporary-setting-values [server.settings/hide-stacktraces true]
(let [exception (ex-info "Validation failed"
{:status-code 400
- :errors {:email "Invalid email format"
+ :params {:password "hunter2"}
+ :errors {:email "Invalid email format"
:password "Password too short"}})
response (mw.exceptions/api-exception-response exception nil)]
(is (= 400 (:status response)))
diff --git a/test/metabase/server/streaming_response_test.clj b/test/metabase/server/streaming_response_test.clj
index d6cddeb366c..044df23bb3a 100644
--- a/test/metabase/server/streaming_response_test.clj
+++ b/test/metabase/server/streaming_response_test.clj
@@ -2,6 +2,7 @@
(:require
[clj-http.client :as http]
[clojure.core.async :as a]
+ [clojure.string :as str]
[clojure.test :refer :all]
[clojure.walk :as walk]
[compojure.response]
@@ -374,7 +375,7 @@
(testing "write-error! includes stacktrace and exception chain when hide-stacktraces is false"
(mt/with-temporary-setting-values [hide-stacktraces false]
(with-open [os (java.io.ByteArrayOutputStream.)]
- (let [exception (ex-info "Test error message" {:custom-data "test-value"})]
+ (let [exception (ex-info "Test error message" {:custom-data "test-value", :query "SELECT secret", :response/keys #{:custom-data}})]
(#'streaming-response/write-error! os exception :api)
(let [error-response (json/decode (String. (.toByteArray os) "UTF-8") true)]
(is (= "Test error message" (:cause error-response))
@@ -386,13 +387,15 @@
(is (contains? error-response :via)
"Response should contain :via key")
(is (= "test-value" (get-in error-response [:data :custom-data]))
- "Response should include custom data from ex-info")))))))
+ "Response should include the listed ex-data")
+ (is (not (str/includes? (pr-str error-response) "SELECT secret"))
+ "Response should not include unlisted ex-data")))))))
(deftest write-error-omits-stacktrace-when-hide-stacktraces-enabled-test
(testing "write-error! omits stacktrace and exception chain when hide-stacktraces is true"
(mt/with-temporary-setting-values [hide-stacktraces true]
(with-open [os (java.io.ByteArrayOutputStream.)]
- (let [exception (ex-info "Test error message with sensitive info" {:custom-data "test-value"})]
+ (let [exception (ex-info "Test error message with sensitive info" {:custom-data "test-value", :query "SELECT secret", :response/keys #{:custom-data}})]
(#'streaming-response/write-error! os exception :api)
(let [error-response (json/decode (String. (.toByteArray os) "UTF-8") true)]
(is (= "Test error message with sensitive info" (:cause error-response))
@@ -402,7 +405,9 @@
(is (not (contains? error-response :via))
"Response should not contain :via key")
(is (not (contains? error-response :data))
- "Response should not contain the ex-data either, like the regular exception middleware")))))))
+ "Response should not contain the ex-data either, like the regular exception middleware")
+ (is (not (str/includes? (pr-str error-response) "SELECT secret"))
+ "Response should not include unlisted ex-data")))))))
(deftest write-error-nested-exception-with-stacktraces-disabled-test
(testing "write-error! includes nested exception details when hide-stacktraces is false"
@@ -492,7 +497,7 @@
(let [output (String. (.toByteArray baos) "UTF-8")]
(is (= {:status "failed"
:error "generic message"
- :original-keys ["cause" "data" "trace" "via"]}
+ :original-keys ["cause" "trace" "via"]}
(json/decode output true)))
(is (not (re-find #"SENSITIVE" output))))))
(testing "for an already-formatted error map"
@@ -553,7 +558,7 @@
(is (= 500 status))
(is (= {:status "failed"
:error "generic message"
- :original-keys ["cause" "data" "trace" "via"]}
+ :original-keys ["cause" "trace" "via"]}
(json/decode body true)))
(is (not (re-find #"SENSITIVE" body)))))
(testing "an error map the body writes itself with write-error!, as the query processor does"
diff --git a/test/metabase/settings/models/setting_test.clj b/test/metabase/settings/models/setting_test.clj
index 519e78a4217..e18e2cd8803 100644
--- a/test/metabase/settings/models/setting_test.clj
+++ b/test/metabase/settings/models/setting_test.clj
@@ -1320,7 +1320,7 @@
:setting "test-feature-setting"
:feature :test-feature}
(try (test-feature-setting! "custom")
- (catch ExceptionInfo e (ex-data e)))))))
+ (catch ExceptionInfo e (dissoc (ex-data e) :response/keys)))))))
(testing ":enabled? returns false"
(is (= {:status-code 400
:setting "test-enabled-setting-default"}
diff --git a/test/metabase/tiles/api_test.clj b/test/metabase/tiles/api_test.clj
index 18449adceed..abec3b90246 100644
--- a/test/metabase/tiles/api_test.clj
+++ b/test/metabase/tiles/api_test.clj
@@ -272,12 +272,14 @@
(deftest ^:parallel failure-test
(testing "if the query fails, don't attempt to generate a map without any points -- the endpoint should return a 400"
- (is (=? {:status "failed"}
- (mt/user-http-request
- :rasta :get 400 "tiles/1/1/1"
- :latField (encoded-lat-field-ref :mbql)
- :lonField (encoded-lon-field-ref :mbql)
- :query (json/encode (mt/mbql-query people {:filter [:= $people.id "X"]})))))))
+ (let [body (mt/user-http-request
+ :rasta :get 400 "tiles/1/1/1"
+ :latField (encoded-lat-field-ref :mbql)
+ :lonField (encoded-lon-field-ref :mbql)
+ :query (json/encode (mt/mbql-query people {:filter [:= $people.id "X"]})))]
+ (is (re-find #"^Error running tiles query" body))
+ (testing "the query processor's error map, which carries the query, stays server-side"
+ (is (string? body))))))
(deftest ^:parallel ad-hoc-implicit-join-ref-test
(testing "GET /api/tiles/:zoom/:x/:y returns a 400 when the lat/lon refs use an implicit join (:source-field)"
diff --git a/test/metabase/util/api_error_test.clj b/test/metabase/util/api_error_test.clj
new file mode 100644
index 00000000000..ff43bcc2555
--- /dev/null
+++ b/test/metabase/util/api_error_test.clj
@@ -0,0 +1,60 @@
+(ns metabase.util.api-error-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.util.api-error :as api-error]))
+
+(deftest ^:parallel extend-response-keys-test
+ (testing "lists keys as client-facing without renaming them"
+ (is (= {:status-code 400, :detail {:id "bad"}, :card-id 1, :response/keys #{:detail}}
+ (api-error/extend-response-keys {:status-code 400, :detail {:id "bad"}, :card-id 1} :detail))))
+ (testing "adds to keys already listed"
+ (is (= #{:detail :field}
+ (:response/keys (-> {:detail 1, :field "x"}
+ (api-error/extend-response-keys :detail)
+ (api-error/extend-response-keys :field))))))
+ (testing "works on nil"
+ (is (= {:response/keys #{:detail}} (api-error/extend-response-keys nil :detail))))
+ (testing "no keys leaves the data as it is"
+ (is (= {:status-code 404} (api-error/extend-response-keys {:status-code 404})))))
+
+(deftest ^:parallel response-data-test
+ (testing "only the listed keys are returned"
+ (is (= {:detail {:id "bad"}, :field "x"}
+ (api-error/response-data {:status-code 400
+ :query {:secret "SELECT"}
+ :detail {:id "bad"}
+ :field "x"
+ :response/keys #{:detail :field}}))))
+ (testing "listed keys that are absent are skipped"
+ (is (= {:detail 1}
+ (api-error/response-data {:detail 1, :response/keys #{:detail :message}}))))
+ (testing "validation `:errors` are client-facing without being listed"
+ (is (= {:errors {:name "required"}}
+ (api-error/response-data {:status-code 400, :errors {:name "required"}, :query {}}))))
+ (testing "error codes, in either spelling, are client-facing without being listed"
+ (is (= {:error-code "x", :error_code "y"}
+ (api-error/response-data {:status-code 400, :error-code "x", :error_code "y", :query {}}))))
+ (testing "messages, under `:message` or `:error_message`, are client-facing without being listed"
+ (is (= {:message "Not allowed", :error_message "Forbidden"}
+ (api-error/response-data {:status-code 403, :message "Not allowed", :error_message "Forbidden", :query {}}))))
+ (testing "`:error` is client-facing without being listed"
+ (is (= {:error "Invalid settings"}
+ (api-error/response-data {:status-code 400, :error "Invalid settings", :query {}})))
+ (is (= {:error "Invalid settings", :detail 1}
+ (api-error/response-data {:error "Invalid settings", :detail 1, :response/keys #{:detail}}))))
+ (testing "nothing listed returns an empty map"
+ (is (= {} (api-error/response-data {:status-code 403, :query {}})))
+ (is (= {} (api-error/response-data nil)))))
+
+(deftest ^:parallel throwable->map-test
+ (testing "every `:data` in the Throwable->map is reduced to its client-facing part and status code"
+ (let [e (ex-info "outer" {:status-code 400, :query {:secret 1}, :detail {:a 1}, :response/keys #{:detail}}
+ (ex-info "inner" {:sql "SELECT secret"}))
+ m (api-error/throwable->map e)]
+ (is (= "inner" (:cause m)))
+ (is (not (contains? m :data))
+ "the root cause has no client-facing data")
+ (is (= [{:detail {:a 1}, :status-code 400} nil]
+ (map :data (:via m)))
+ "`:status-code` is kept with the client-facing data")
+ (is (seq (:trace m))))))
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index 53f5625d1b8..bf521202d7c 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -841,9 +841,9 @@
(mt/with-temp [:model/Database {db-id :id} {:engine :h2
:settings {:api-test-disabled-for-database false}}]
(is (= "Setting api-test-disabled-for-database is not enabled for this database"
- (:message (mt/user-http-request :crowberto :put 400
- (format "database/%s" db-id)
- {:settings {:api-test-disabled-for-database true}}))))))
+ (mt/user-http-request :crowberto :put 400
+ (format "database/%s" db-id)
+ {:settings {:api-test-disabled-for-database true}})))))
(testing "should not validate settings being reset to nil (default)"
;; Resetting a setting to nil should always be allowed, even if the setting would fail validation
(mt/with-temp [:model/Database {db-id :id} {:engine :h2