Skip to content

Commit

Permalink
Improved error handling for invalid API parameters - closes #553
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 17, 2024
1 parent a30a44a commit badb8e6
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 5.2.0 (unreleased)

- Improved error handling for invalid API parameters

## 5.1.0 (2024-03-26)

- Added support for Trilogy
Expand Down
15 changes: 13 additions & 2 deletions app/controllers/ahoy/events_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,23 @@ def create
begin
ActiveSupport::JSON.decode(data)
rescue ActiveSupport::JSON.parse_error
# do nothing
# TODO change to nil in Ahoy 6
[]
end
end

events.first(Ahoy.max_events_per_request).each do |event|
max_events_per_request = Ahoy.max_events_per_request

# check before creating any events
unless events.is_a?(Array) && events.first(max_events_per_request).all? { |v| v.is_a?(Hash) }
logger.info "[ahoy] Invalid parameters"
# :unprocessable_entity is probably more correct
# but keep consistent with missing parameters for now
render plain: "Invalid parameters\n", status: :bad_request
return
end

events.first(max_events_per_request).each do |event|
time = Time.zone.parse(event["time"]) rescue nil

# timestamp is deprecated
Expand Down
26 changes: 26 additions & 0 deletions test/api_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,32 @@ def test_event_bad_json
assert_equal 0, Ahoy::Event.count
end

def test_event_bad_array
visit = random_visit

event_params = {
visit_token: visit.visit_token,
visitor_token: visit.visitor_token,
events_json: "null"
}
post ahoy_engine.events_url, params: event_params
assert_response :bad_request
assert_equal "Invalid parameters\n", response.body
end

def test_event_bad_element
visit = random_visit

event_params = {
visit_token: visit.visit_token,
visitor_token: visit.visitor_token,
events_json: "[null]"
}
post ahoy_engine.events_url, params: event_params
assert_response :bad_request
assert_equal "Invalid parameters\n", response.body
end

def test_before_action
post ahoy_engine.visits_url, params: {visit_token: random_token, visitor_token: random_token}
assert_nil controller.ran_before_action
Expand Down

0 comments on commit badb8e6

Please sign in to comment.