From ba7c090d0223c6240241b8eed943ab93bbd6119f Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 16 Aug 2016 00:12:23 +0100 Subject: [PATCH] Redirect to home page on invalid urls Every now and again we get invalid urls which causes the check for unknown formats to blow up. In these circumstances we should catch the invalid URI error and redirect to the home page. --- app/controllers/application_controller.rb | 2 ++ spec/controllers/application_controller_spec.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 0c98b2016..acf85b36f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -29,6 +29,8 @@ def url_without_format URI.parse(request.original_url).tap do |uri| uri.path = File.join(File.dirname(request.path), File.basename(request.path, '.*')) end.to_s + rescue URI::InvalidURIError => e + home_url end def redirect_to_url_without_format diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index 8269bb4f8..589077421 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -100,4 +100,18 @@ def index expect(controller.class.helpers).to respond_to :public_petition_facets end end + + context "when the url has an invalid format" do + let(:exception) { URI::InvalidURIError.new } + + before do + allow(request).to receive(:format).and_return(nil) + allow(request).to receive(:original_url).and_return("https://petition.parliament.uk/petitions.json]") + end + + it "redirects to the home page" do + get :index + expect(response).to redirect_to("https://petition.parliament.uk/") + end + end end