From aa6e5ae79977e41f3a9fc9ccc98baeaec4660774 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Thu, 3 Mar 2022 14:07:04 +1100 Subject: [PATCH] Report useful error message in missing parameter --- app/controllers/api/v1/base_controller.rb | 8 ++++++++ config/locales/en.yml | 1 + spec/requests/api/v1/customers_spec.rb | 5 ++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index 4402873e69..39f9e1684b 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -19,6 +19,7 @@ module Api rescue_from CanCan::AccessDenied, with: :unauthorized rescue_from ActiveRecord::RecordNotFound, with: :not_found rescue_from Pagy::VariableError, with: :invalid_pagination + rescue_from ActionController::ParameterMissing, with: :missing_parameter rescue_from ActionController::UnpermittedParameters, with: :unpermitted_parameters private @@ -62,6 +63,13 @@ module Api json: json_api_error(exception.message) end + def missing_parameter(error) + message = I18n.t(:missing_parameter, param: error.param, scope: :api) + + render status: :unprocessable_entity, + json: json_api_error(message) + end + def unpermitted_parameters(error) message = I18n.t(:unpermitted_parameters, params: error.params.join(", "), scope: :api) diff --git a/config/locales/en.yml b/config/locales/en.yml index 56dc356d3b..7fea74e856 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1413,6 +1413,7 @@ en: invalid_api_key: "Invalid API key (%{key}) specified." unauthorized: "You are not authorized to perform that action." unpermitted_parameters: "Parameters not allowed in this request: %{params}" + missing_parameter: "A required parameter is missing or empty: %{param}" invalid_resource: "Invalid resource. Please fix errors and try again." resource_not_found: "The resource you were looking for could not be found." enterprise_logo: diff --git a/spec/requests/api/v1/customers_spec.rb b/spec/requests/api/v1/customers_spec.rb index d4d7a235b5..a6a620b398 100644 --- a/spec/requests/api/v1/customers_spec.rb +++ b/spec/requests/api/v1/customers_spec.rb @@ -161,7 +161,10 @@ describe "Customers", type: :request do param(:customer) { {} } schema "$ref": "#/components/schemas/error_response" - run_test! + run_test! do + expect(json_error_detail).to eq "A required parameter is missing or empty: customer" + expect(json_response[:meta]).to eq nil + end end end end