request_exception_handler 0.3

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2009 Karol Bucek
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,69 @@
1
+ RequestExceptionHandler
2
+ =======================
3
+
4
+ Rails is not capable of calling Your exception handlers when an error occurs
5
+ during the parsing of request parameters (e.g. in case of invalid XML body).
6
+
7
+ This will hopefully change someday, but until then I have created this biutiful
8
+ monkey-patch for request parameter parsing to allow more flexibility when
9
+ an invalid request body is received.
10
+
11
+ Code has been tested on 2.3, 2.2.3 and 2.1 as well as on Rails 3.0 / 3.1.
12
+
13
+
14
+ Install
15
+ =======
16
+
17
+ gem 'request_exception_handler'
18
+
19
+ or as a plain-old rails plugin :
20
+
21
+ script/plugin install git://github.com/kares/request_exception_handler.git
22
+
23
+ Example
24
+ =======
25
+
26
+ The code hooks into parameter parsing and allows a request to be constructed
27
+ even if the params can not be parsed from the submitted raw content. A before
28
+ filter is installed that checks for a request exception and re-raises it thus
29
+ it seems to Rails that the exception comes from the application code and is
30
+ processed as all other "business" exceptions.
31
+ You might skip this filter and install Your own to handle such cases (it's good
32
+ to make sure the filter gets to the beginning of the chain) :
33
+
34
+ class MyController < ApplicationController
35
+
36
+ skip_before_filter :check_request_exception # filter the plugin installed
37
+
38
+ # custom before filter use request_exception to detect occured errors
39
+ prepend_before_filter :return_409_on_json_errors
40
+
41
+ private
42
+
43
+ def return_409_on_json_errors
44
+ if re = request_exception && re.is_a?(ActiveSupport::JSON::ParseError)
45
+ head 409
46
+ else
47
+ head 500
48
+ end
49
+ end
50
+
51
+ end
52
+
53
+ Another option of how to modify the returned 500 status is to use exception
54
+ handlers the same way You're (hopefully) using them for Your own exceptions :
55
+
56
+ class ApplicationController < ActionController::Base
57
+
58
+ rescue_from 'REXML::ParseException' do |exception|
59
+ render :text => exception.to_s, :status => 422
60
+ end
61
+
62
+ end
63
+
64
+ If You're not using REXML as a parsing backend the exception might vary, e.g.
65
+ for Nokogiri the rescue block would look something like :
66
+
67
+ rescue_from 'Nokogiri::XML::SyntaxError' do |exception|
68
+ render :text => exception.to_s, :status => 422
69
+ end
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the request_exception_handler plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << 'lib'
11
+ t.pattern = 'test/*_test.rb'
12
+ t.verbose = true
13
+ end
14
+
15
+ desc 'Generate documentation for the request_exception_handler plugin.'
16
+ Rake::RDocTask.new(:rdoc) do |rdoc|
17
+ rdoc.rdoc_dir = 'rdoc'
18
+ rdoc.title = 'RequestExceptionHandler'
19
+ rdoc.options << '--line-numbers' << '--inline-source'
20
+ rdoc.rdoc_files.include('README')
21
+ rdoc.rdoc_files.include('lib/**/*.rb')
22
+ end
@@ -0,0 +1,120 @@
1
+
2
+ module RequestExceptionHandler
3
+
4
+ @@parse_request_parameters_exception_handler = lambda do |request, exception|
5
+ Thread.current[:request_exception] = exception
6
+ request_body = request.respond_to?(:body) ? request.body : request.raw_post
7
+
8
+ logger = RequestExceptionHandler.logger
9
+ if logger.info?
10
+ content_log = request_body
11
+ if request_body.is_a?(StringIO)
12
+ pos = request_body.pos
13
+ content_log = request_body.read
14
+ end
15
+ logger.info "#{exception.class.name} occurred while parsing request parameters." +
16
+ "\nContents:\n#{content_log}\n"
17
+ request_body.pos = pos if pos
18
+ end
19
+
20
+ content_type = if request.respond_to?(:content_type_with_parameters)
21
+ request.send :content_type_with_parameters # AbstractRequest
22
+ else # rack request
23
+ request.respond_to?(:content_mime_type) ? request.content_mime_type : request.content_type
24
+ end
25
+ { "body" => request_body, "content_type" => content_type, "content_length" => request.content_length }
26
+ end
27
+
28
+ mattr_accessor :parse_request_parameters_exception_handler
29
+
30
+ def self.reset_request_exception
31
+ Thread.current[:request_exception] = nil
32
+ end
33
+
34
+ def self.logger
35
+ defined?(Rails.logger) ? Rails.logger :
36
+ defined?(RAILS_DEFAULT_LOGGER) ? RAILS_DEFAULT_LOGGER :
37
+ Logger.new($stderr)
38
+ end
39
+
40
+ def self.included(base)
41
+ base.prepend_before_filter :check_request_exception
42
+ end
43
+
44
+ def check_request_exception
45
+ e = request_exception
46
+ raise e if e && e.is_a?(Exception)
47
+ end
48
+
49
+ def request_exception
50
+ return @_request_exception if defined? @_request_exception
51
+ @_request_exception = Thread.current[:request_exception]
52
+ RequestExceptionHandler.reset_request_exception
53
+ @_request_exception
54
+ end
55
+
56
+ end
57
+
58
+ require 'action_controller/base'
59
+ ActionController::Base.send :include, RequestExceptionHandler
60
+
61
+ # NOTE: Rails monkey patching follows :
62
+
63
+ if defined? ActionDispatch::ParamsParser # Rails 3.x
64
+
65
+ ActionDispatch::ParamsParser.class_eval do
66
+
67
+ def parse_formatted_parameters_with_exception_handler(env)
68
+ begin
69
+ out = parse_formatted_parameters_without_exception_handler(env)
70
+ RequestExceptionHandler.reset_request_exception # make sure it's nil
71
+ out
72
+ rescue Exception => e # YAML, XML or Ruby code block errors
73
+ handler = RequestExceptionHandler.parse_request_parameters_exception_handler
74
+ handler ? handler.call(ActionDispatch::Request.new(env), e) : raise
75
+ end
76
+ end
77
+
78
+ alias_method_chain :parse_formatted_parameters, :exception_handler
79
+
80
+ end
81
+
82
+ elsif defined? ActionController::ParamsParser # Rails 2.3.x
83
+
84
+ ActionController::ParamsParser.class_eval do
85
+
86
+ def parse_formatted_parameters_with_exception_handler(env)
87
+ begin
88
+ out = parse_formatted_parameters_without_exception_handler(env)
89
+ RequestExceptionHandler.reset_request_exception # make sure it's nil
90
+ out
91
+ rescue Exception => e # YAML, XML or Ruby code block errors
92
+ handler = RequestExceptionHandler.parse_request_parameters_exception_handler
93
+ handler ? handler.call(ActionController::Request.new(env), e) : raise
94
+ end
95
+ end
96
+
97
+ alias_method_chain :parse_formatted_parameters, :exception_handler
98
+
99
+ end
100
+
101
+ else # old-style Rails < 2.3
102
+
103
+ ActionController::AbstractRequest.class_eval do
104
+
105
+ def parse_formatted_request_parameters_with_exception_handler
106
+ begin
107
+ out = parse_formatted_request_parameters_without_exception_handler
108
+ RequestExceptionHandler.reset_request_exception # make sure it's nil
109
+ out
110
+ rescue Exception => e # YAML, XML or Ruby code block errors
111
+ handler = RequestExceptionHandler.parse_request_parameters_exception_handler
112
+ handler ? handler.call(self, e) : raise
113
+ end
114
+ end
115
+
116
+ alias_method_chain :parse_formatted_request_parameters, :exception_handler
117
+
118
+ end
119
+
120
+ end
@@ -0,0 +1,201 @@
1
+ require File.expand_path('test_helper', File.dirname(__FILE__))
2
+
3
+ #
4
+ # NOTE: due to the test_helper.rb argument parsing this test might
5
+ # be run with different versions of Rails e.g. :
6
+ #
7
+ # ruby request_exception_handler_test.rb RAILS_VERSION=2.1.2
8
+ #
9
+
10
+ class TestController < ActionController::Base
11
+
12
+ def parse
13
+ head :ok
14
+ end
15
+
16
+ def parse_with_check_request_exception_skipped
17
+ head :ok
18
+ end
19
+
20
+ skip_before_filter :check_request_exception, :only =>
21
+ [ :parse_with_check_request_exception_skipped, :parse_with_check_request_exception_replaced ]
22
+
23
+ def parse_with_check_request_exception_replaced
24
+ head :ok
25
+ end
26
+
27
+ before_filter :return_501_on_request_exception, :only => [ :parse_with_check_request_exception_replaced ]
28
+
29
+ def return_501_on_request_exception
30
+ head 501 if request_exception
31
+ end
32
+
33
+ end
34
+
35
+ class TestWithRexmlRescueController < ActionController::Base
36
+
37
+ rescue_from 'REXML::ParseException' do |exception|
38
+ render :text => exception.class.name, :status => 405
39
+ end
40
+
41
+ def index
42
+ head :ok
43
+ end
44
+
45
+ end
46
+
47
+ class TestWithNokogiriRescueController < ActionController::Base
48
+
49
+ rescue_from 'Nokogiri::XML::SyntaxError' do |exception|
50
+ render :text => exception.class.name, :status => 505
51
+ end
52
+
53
+ def index
54
+ head :ok
55
+ end
56
+
57
+ end
58
+
59
+ if Rails.version < '3.0.0'
60
+ ActionController::Routing::Routes.draw do |map|
61
+ map.connect '/parse_with_rexml_rescue_block',
62
+ :controller => 'test_with_rexml_rescue', :action => 'index'
63
+ map.connect '/parse_with_nokogiri_rescue_block',
64
+ :controller => 'test_with_nokogiri_rescue', :action => 'index'
65
+ map.connect '/:action', :controller => "test"
66
+ end
67
+ else
68
+ RequestExceptionHandlerTest::Application.routes.draw do
69
+ match "/parse_with_rexml_rescue_block", :to => 'test_with_rexml_rescue#index'
70
+ match "/parse_with_nokogiri_rescue_block", :to => 'test_with_nokogiri_rescue#index'
71
+ match '/parse' => "test#parse"
72
+ match '/parse_with_check_request_exception_skipped', :to => "test#parse_with_check_request_exception_skipped"
73
+ match '/parse_with_check_request_exception_replaced', :to => "test#parse_with_check_request_exception_replaced"
74
+ end
75
+ end
76
+
77
+ class RequestExceptionHandlerJsonTest < ActionController::IntegrationTest
78
+
79
+ def test_parse_valid_json
80
+ post "/parse", '{"cicinbrus": {"name": "Ferko"}}', 'CONTENT_TYPE' => 'application/json'
81
+ assert_response 200
82
+ end
83
+
84
+ def test_parse_invalid_json_returns_500_by_default
85
+ post "/parse", '{"cicinbrus": {"name": "Ferko"}', 'CONTENT_TYPE' => 'application/json'
86
+ assert_response 500
87
+ end
88
+
89
+ def test_request_exception_returns_parse_exception_on_invalid_json_request
90
+ post "/parse", "{\"cicinbrus\": {\"name: \"Ferko\"}}", 'CONTENT_TYPE' => 'application/json'
91
+ assert_not_nil controller.request_exception
92
+ assert_json_parse_exception controller.request_exception
93
+ end
94
+
95
+ private
96
+
97
+ def assert_json_parse_exception(error)
98
+ if ActiveSupport::JSON.respond_to?(:parse_error) # 2.3.5
99
+ parse_error_class = ActiveSupport::JSON.parse_error
100
+ assert_instance_of parse_error_class, error
101
+ else
102
+ assert_instance_of ActiveSupport::JSON::ParseError, error
103
+ end
104
+ end
105
+
106
+ end
107
+
108
+ class RequestExceptionHandlerXmlTest < ActionController::IntegrationTest
109
+
110
+ def test_parse_valid_xml
111
+ post "/parse", "<cicinbrus> <name>Ferko</name> </cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
112
+ assert_response 200
113
+ end
114
+
115
+ def test_parse_invalid_xml_returns_500_by_default
116
+ post "/parse", "<cicinbrus> <name>Ferko<name> </cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
117
+ assert_response 500
118
+ end
119
+
120
+ def test_controller_responds_to_request_exception_and_returns_nil_on_valid_request
121
+ post "/parse"
122
+ assert controller.respond_to? :request_exception
123
+ assert_nil controller.request_exception
124
+ end
125
+
126
+ def test_controller_returns_nil_on_request_exception_with_check_request_exception_skipped
127
+ post "/parse_with_check_request_exception_skipped"
128
+ assert_nil controller.request_exception
129
+ end
130
+
131
+ def test_request_exception_returns_parse_exception_on_invalid_xml_request
132
+ post "/parse", "<cicinbrus> <name>Ferko</namee> </cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
133
+ assert_not_nil controller.request_exception
134
+ assert_xml_parse_exception controller.request_exception
135
+ end
136
+
137
+ def test_request_exception_gets_cleared_for_another_valid_request
138
+ post "/parse", "<cicinbrus> <name>Ferko</name> </cicinbrus ", 'CONTENT_TYPE' => 'application/xml'
139
+ post "/parse", "<cicinbrus> <name>Ferko</name> </cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
140
+ assert_nil controller.request_exception
141
+ end
142
+
143
+ def test_request_exception_gets_cleared_for_another_valid_request_with_check_request_exception_skipped
144
+ post "/parse_with_check_request_exception_skipped",
145
+ "<cicinbrus> <name>Ferko</name> </cicinbrus ", 'CONTENT_TYPE' => 'application/xml'
146
+ post "/parse_with_check_request_exception_skipped",
147
+ "<cicinbrus> <name>Ferko</name> </cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
148
+ assert_nil controller.request_exception
149
+ end
150
+
151
+ def test_parse_with_check_request_exception_skipped_does_not_reraise_parse_exception
152
+ post "/parse_with_check_request_exception_skipped",
153
+ "<cicinbrus> <name>Ferko</name> </cicinbrus ", 'CONTENT_TYPE' => 'application/xml'
154
+
155
+ assert_not_nil controller.request_exception
156
+ assert_response 200
157
+ end
158
+
159
+ def test_parse_with_check_request_exception_replaced_does_return_501_on_parse_exception
160
+ post "/parse_with_check_request_exception_replaced",
161
+ "<cicinbrus> <name>Ferko</name> <cicinbrus>", 'CONTENT_TYPE' => 'application/xml'
162
+ assert_response 501
163
+ end
164
+
165
+ def test_on_parse_error_custom_rescue_handler_gets_called
166
+ post "/parse_with_rexml_rescue_block", "<cicinbrus> <name>Ferko</name>", 'CONTENT_TYPE' => 'application/xml'
167
+ assert_response 405
168
+ end
169
+
170
+ if Rails.version >= '2.3'
171
+
172
+ def test_on_parse_error_custom_rescue_handler_gets_called_for_nokogiri
173
+ nokogiri =
174
+ begin
175
+ require 'nokogiri'
176
+ rescue LoadError
177
+ :nil
178
+ end
179
+ if nokogiri != :nil
180
+ backend = ActiveSupport::XmlMini.backend
181
+ begin
182
+ ActiveSupport::XmlMini.backend = 'Nokogiri'
183
+ post "/parse_with_nokogiri_rescue_block", "<cicinbrus> <name>Ferko</name>", 'CONTENT_TYPE' => 'application/xml'
184
+ assert_response 505
185
+ ensure
186
+ ActiveSupport::XmlMini.backend = backend
187
+ end
188
+ else
189
+ puts "nokogiri not available - test skipped !"
190
+ end
191
+ end
192
+
193
+ end
194
+
195
+ private
196
+
197
+ def assert_xml_parse_exception(error)
198
+ assert_instance_of REXML::ParseException, error
199
+ end
200
+
201
+ end
@@ -0,0 +1,153 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+
4
+ # enable testing with different version of rails via argv :
5
+ # ruby request_exception_handler_test.rb RAILS_VERSION=2.2.2
6
+
7
+ version =
8
+ if ARGV.find { |opt| /RAILS_VERSION=([\d\.]+)/ =~ opt }
9
+ $~[1]
10
+ else
11
+ # rake test RAILS_VERSION=2.3.5
12
+ ENV['RAILS_VERSION']
13
+ end
14
+
15
+ if version
16
+ RAILS_VERSION = version
17
+ gem 'activesupport', "= #{RAILS_VERSION}"
18
+ gem 'activerecord', "= #{RAILS_VERSION}"
19
+ gem 'actionpack', "= #{RAILS_VERSION}"
20
+ gem 'actionmailer', "= #{RAILS_VERSION}"
21
+ gem 'rails', "= #{RAILS_VERSION}"
22
+ else
23
+ gem 'activesupport'
24
+ gem 'activerecord'
25
+ gem 'actionpack'
26
+ gem 'actionmailer'
27
+ gem 'rails'
28
+ end
29
+
30
+ require 'active_support'
31
+ require 'active_support/test_case'
32
+ require 'action_controller'
33
+ require 'action_controller/test_case'
34
+
35
+ require 'rails/version'
36
+ puts "emulating Rails.version = #{Rails::VERSION::STRING}"
37
+
38
+ require 'action_controller/integration' if Rails::VERSION::MAJOR < 3
39
+ require 'action_controller/session_management' if Rails::VERSION::MAJOR < 3
40
+ require 'action_dispatch' if Rails::VERSION::MAJOR >= 3
41
+ require 'action_dispatch/routing' if Rails::VERSION::MAJOR >= 3
42
+
43
+ if Rails::VERSION::MAJOR >= 3
44
+ ActiveSupport::Deprecation.behavior = :stderr
45
+ else
46
+ ActiveSupport::Deprecation.debug = true
47
+ end
48
+
49
+ if Rails::VERSION::MAJOR >= 3
50
+ require 'rails'
51
+ # a minimal require 'rails/all' :
52
+ require "action_controller/railtie"
53
+ require "rails/test_unit/railtie"
54
+ require 'rails/test_help'
55
+ else
56
+ module Rails
57
+ class << self
58
+
59
+ def initialized?
60
+ @initialized || false
61
+ end
62
+
63
+ def initialized=(initialized)
64
+ @initialized ||= initialized
65
+ end
66
+
67
+ def backtrace_cleaner
68
+ @@backtrace_cleaner ||=
69
+ begin
70
+ require 'rails/gem_dependency' # backtrace_cleaner depends on this !
71
+ require 'rails/backtrace_cleaner'
72
+ Rails::BacktraceCleaner.new
73
+ rescue LoadError
74
+ nil
75
+ end
76
+ end
77
+
78
+ def root
79
+ require 'pathname'
80
+ Pathname.new(RAILS_ROOT)
81
+ end
82
+
83
+ def env
84
+ @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
85
+ end
86
+
87
+ def cache
88
+ RAILS_CACHE
89
+ end
90
+
91
+ def version
92
+ VERSION::STRING
93
+ end
94
+
95
+ def public_path
96
+ @@public_path ||= self.root ? File.join(self.root, "public") : "public"
97
+ end
98
+
99
+ def public_path=(path)
100
+ @@public_path = path
101
+ end
102
+
103
+ end
104
+ end
105
+ end
106
+
107
+ silence_warnings { RAILS_ROOT = File.expand_path( File.dirname(__FILE__) ) }
108
+
109
+ # Make double-sure the RAILS_ENV is set to test,
110
+ # so fixtures are loaded to the right database
111
+ silence_warnings { RAILS_ENV = "test" }
112
+
113
+ Rails.backtrace_cleaner.remove_silencers! if Rails.backtrace_cleaner
114
+
115
+ module Rails # make sure we can set the logger
116
+ class << self
117
+ attr_accessor :logger
118
+ end
119
+ end
120
+
121
+ File.open(File.join(File.dirname(__FILE__), 'test.log'), 'w') do |file|
122
+ Rails.logger = Logger.new(file.path)
123
+ end
124
+
125
+ if ActionController::Base.respond_to? :session_options # Rails 2.x
126
+
127
+ skey = Rails.version < '2.3' ? :session_key : :key
128
+ ActionController::Base.session_options[skey] = '_request_exception_handler_test'
129
+ ActionController::Base.session_options[:secret] = 'x' * 30
130
+
131
+ else # since Rails 3.0.0 :
132
+
133
+ module RequestExceptionHandlerTest
134
+ class Application < Rails::Application
135
+ config.secret_token = 'x' * 30
136
+ end
137
+ end
138
+
139
+ # Initialize the rails application
140
+ RequestExceptionHandlerTest::Application.initialize!
141
+
142
+ end
143
+
144
+ ActiveSupport::TestCase.class_eval do
145
+
146
+ def setup_fixtures
147
+ return nil # Rails 3 load hooks !
148
+ end
149
+
150
+ end
151
+
152
+ $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '../lib')
153
+ require 'request_exception_handler'
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: request_exception_handler
3
+ version: !ruby/object:Gem::Version
4
+ hash: 13
5
+ prerelease:
6
+ segments:
7
+ - 0
8
+ - 3
9
+ version: "0.3"
10
+ platform: ruby
11
+ authors:
12
+ - Karol Bucek
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2011-08-31 00:00:00 +02:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: actionpack
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ hash: 1
29
+ segments:
30
+ - 2
31
+ - 1
32
+ version: "2.1"
33
+ type: :runtime
34
+ version_requirements: *id001
35
+ description: a rails hook that allows one to handle request parameter parsing exceptions (invalid XML, JSON) with a rescue block
36
+ email:
37
+ - self@kares.org
38
+ executables: []
39
+
40
+ extensions: []
41
+
42
+ extra_rdoc_files:
43
+ - README.md
44
+ files:
45
+ - lib/request_exception_handler.rb
46
+ - LICENSE
47
+ - README.md
48
+ - Rakefile
49
+ - test/request_exception_handler_test.rb
50
+ - test/test_helper.rb
51
+ has_rdoc: true
52
+ homepage: http://github.com/kares/request_exception_handler
53
+ licenses: []
54
+
55
+ post_install_message:
56
+ rdoc_options: []
57
+
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ none: false
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ hash: 3
66
+ segments:
67
+ - 0
68
+ version: "0"
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ none: false
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ hash: 3
75
+ segments:
76
+ - 0
77
+ version: "0"
78
+ requirements: []
79
+
80
+ rubyforge_project: "[none]"
81
+ rubygems_version: 1.6.1
82
+ signing_key:
83
+ specification_version: 3
84
+ summary: handler for all the request (parsing) related exceptions
85
+ test_files:
86
+ - test/request_exception_handler_test.rb
87
+ - test/test_helper.rb