├── .gitignore
├── .rspec
├── .rubocop.yml
├── .rubocop_todo.yml
├── .ruby-version
├── .travis.yml
├── Gemfile
├── LICENSE.txt
├── README.md
├── Rakefile
├── api_error_handler.gemspec
├── bin
├── console
└── setup
├── lib
├── api_error_handler.rb
└── api_error_handler
│ ├── action_controller.rb
│ ├── error_id_generator.rb
│ ├── error_reporter.rb
│ ├── errors.rb
│ ├── serializers
│ ├── base_serializer.rb
│ ├── json.rb
│ ├── json_api.rb
│ └── xml.rb
│ └── version.rb
├── rails_5_test_app
├── .rspec
├── Gemfile
├── Gemfile.lock
├── Rakefile
├── app
│ ├── assets
│ │ ├── config
│ │ │ └── manifest.js
│ │ ├── images
│ │ │ └── .keep
│ │ └── stylesheets
│ │ │ └── application.css
│ ├── channels
│ │ └── application_cable
│ │ │ ├── channel.rb
│ │ │ └── connection.rb
│ ├── controllers
│ │ ├── api_controller.rb
│ │ ├── application_controller.rb
│ │ ├── concerns
│ │ │ └── .keep
│ │ └── tests_controller.rb
│ ├── errors
│ │ └── custom_auth_error.rb
│ ├── helpers
│ │ └── application_helper.rb
│ ├── jobs
│ │ └── application_job.rb
│ ├── mailers
│ │ └── application_mailer.rb
│ ├── models
│ │ ├── application_record.rb
│ │ └── concerns
│ │ │ └── .keep
│ └── views
│ │ └── layouts
│ │ ├── application.html.erb
│ │ ├── mailer.html.erb
│ │ └── mailer.text.erb
├── bin
│ ├── bundle
│ ├── rails
│ ├── rake
│ ├── setup
│ ├── spring
│ ├── update
│ └── yarn
├── config.ru
├── config
│ ├── application.rb
│ ├── boot.rb
│ ├── cable.yml
│ ├── credentials.yml.enc
│ ├── database.yml
│ ├── environment.rb
│ ├── environments
│ │ ├── development.rb
│ │ ├── production.rb
│ │ └── test.rb
│ ├── initializers
│ │ ├── application_controller_renderer.rb
│ │ ├── assets.rb
│ │ ├── backtrace_silencers.rb
│ │ ├── content_security_policy.rb
│ │ ├── cookies_serializer.rb
│ │ ├── filter_parameter_logging.rb
│ │ ├── inflections.rb
│ │ ├── mime_types.rb
│ │ └── wrap_parameters.rb
│ ├── locales
│ │ └── en.yml
│ ├── master.key
│ ├── puma.rb
│ ├── routes.rb
│ ├── spring.rb
│ └── storage.yml
├── db
│ ├── seeds.rb
│ └── test.sqlite3
├── lib
│ ├── assets
│ │ └── .keep
│ └── tasks
│ │ └── .keep
├── package.json
├── public
│ ├── 404.html
│ ├── 422.html
│ ├── 500.html
│ ├── apple-touch-icon-precomposed.png
│ ├── apple-touch-icon.png
│ ├── favicon.ico
│ └── robots.txt
├── spec
│ ├── controllers
│ │ └── tests_controller_spec.rb
│ ├── rails_helper.rb
│ └── spec_helper.rb
├── storage
│ └── .keep
├── test
│ ├── application_system_test_case.rb
│ ├── controllers
│ │ └── .keep
│ ├── fixtures
│ │ ├── .keep
│ │ └── files
│ │ │ └── .keep
│ ├── helpers
│ │ └── .keep
│ ├── integration
│ │ └── .keep
│ ├── mailers
│ │ └── .keep
│ ├── models
│ │ └── .keep
│ ├── system
│ │ └── .keep
│ └── test_helper.rb
└── vendor
│ └── .keep
├── rails_6_test_app
├── .rspec
├── .ruby-version
├── Gemfile
├── Gemfile.lock
├── Rakefile
├── app
│ ├── assets
│ │ ├── config
│ │ │ └── manifest.js
│ │ ├── images
│ │ │ └── .keep
│ │ └── stylesheets
│ │ │ └── application.css
│ ├── controllers
│ │ ├── application_controller.rb
│ │ ├── concerns
│ │ │ └── .keep
│ │ └── tests_controller.rb
│ ├── errors
│ │ └── custom_auth_error.rb
│ ├── helpers
│ │ └── application_helper.rb
│ ├── jobs
│ │ └── application_job.rb
│ ├── models
│ │ ├── application_record.rb
│ │ └── concerns
│ │ │ └── .keep
│ └── views
│ │ └── layouts
│ │ └── application.html.erb
├── bin
│ ├── bundle
│ ├── rails
│ ├── rake
│ ├── setup
│ └── spring
├── config.ru
├── config
│ ├── application.rb
│ ├── boot.rb
│ ├── credentials.yml.enc
│ ├── database.yml
│ ├── environment.rb
│ ├── environments
│ │ ├── development.rb
│ │ ├── production.rb
│ │ └── test.rb
│ ├── initializers
│ │ ├── application_controller_renderer.rb
│ │ ├── backtrace_silencers.rb
│ │ ├── content_security_policy.rb
│ │ ├── cookies_serializer.rb
│ │ ├── filter_parameter_logging.rb
│ │ ├── inflections.rb
│ │ ├── mime_types.rb
│ │ └── wrap_parameters.rb
│ ├── locales
│ │ └── en.yml
│ ├── master.key
│ ├── puma.rb
│ ├── routes.rb
│ ├── spring.rb
│ └── storage.yml
├── db
│ ├── development.sqlite3
│ ├── seeds.rb
│ └── test.sqlite3
├── lib
│ ├── assets
│ │ └── .keep
│ └── tasks
│ │ └── .keep
├── public
│ ├── 404.html
│ ├── 422.html
│ ├── 500.html
│ ├── apple-touch-icon-precomposed.png
│ ├── apple-touch-icon.png
│ ├── favicon.ico
│ └── robots.txt
├── spec
│ ├── controllers
│ │ └── tests_controller_spec.rb
│ ├── rails_helper.rb
│ └── spec_helper.rb
├── storage
│ └── .keep
└── vendor
│ └── .keep
└── spec
├── api_error_handler
├── error_id_generator_spec.rb
├── error_reporter_spec.rb
└── serializers
│ ├── json_api_spec.rb
│ ├── json_spec.rb
│ └── xml_spec.rb
├── api_error_handler_spec.rb
└── spec_helper.rb
/.gitignore:
--------------------------------------------------------------------------------
1 | /.bundle/
2 | /.yardoc
3 | /_yardoc/
4 | /coverage/
5 | /doc/
6 | /pkg/
7 | /spec/reports/
8 | /tmp/
9 |
10 | /Gemfile.lock
11 |
12 | # rspec failure tracking
13 | .rspec_status
14 |
15 | # Stuff to ignore in the test_apps
16 | rails_5_test_app/tmp
17 | rails_5_test_app/log
18 | rails_5_test_app/.byebug_history
19 |
20 | rails_4_test_app/tmp
21 | rails_4_test_app/log
22 | rails_4_test_app/.byebug_history
23 |
24 | rails_6_test_app/tmp
25 | rails_6_test_app/log
26 | rails_6_test_app/.byebug_history
27 |
--------------------------------------------------------------------------------
/.rspec:
--------------------------------------------------------------------------------
1 | --format documentation
2 | --color
3 | --require spec_helper
4 |
--------------------------------------------------------------------------------
/.rubocop.yml:
--------------------------------------------------------------------------------
1 | inherit_from: .rubocop_todo.yml
2 |
3 | AllCops:
4 | TargetRubyVersion: 2.5
5 | Exclude:
6 | - 'vendor/**/*'
7 | - 'rails_*/**/*'
8 |
9 | Style/StringLiterals:
10 | EnforcedStyle: double_quotes
11 |
12 | Metrics/LineLength:
13 | Max: 100
14 |
15 | Style/MethodCallWithoutArgsParentheses:
16 | Enabled: false
17 |
18 | Style/TrailingCommaInArrayLiteral:
19 | EnforcedStyleForMultiline: comma
20 |
21 | Style/TrailingCommaInHashLiteral:
22 | EnforcedStyleForMultiline: comma
23 |
24 | Metrics/BlockLength:
25 | Exclude:
26 | - 'spec/**/*.rb'
27 | - 'api_error_handler.gemspec'
28 |
29 | Style/Documentation:
30 | Enabled: false
31 |
--------------------------------------------------------------------------------
/.rubocop_todo.yml:
--------------------------------------------------------------------------------
1 | # This configuration was generated by
2 | # `rubocop --auto-gen-config --auto-gen-only-exclude --exclude-limit 100`
3 | # on 2019-08-25 13:23:25 +0100 using RuboCop version 0.74.0.
4 | # The point is for the user to remove these configuration records
5 | # one by one as the offenses are removed from the code base.
6 | # Note that changes in the inspected code, or installation of new
7 | # versions of RuboCop, may require this file to be generated again.
8 |
9 | # Offense count: 1
10 | # Cop supports --auto-correct.
11 | # Configuration parameters: TreatCommentsAsGroupSeparators, Include.
12 | # Include: **/*.gemspec
13 | Gemspec/OrderedDependencies:
14 | Exclude:
15 | - 'api_error_handler.gemspec'
16 |
17 | # Offense count: 1
18 | # Cop supports --auto-correct.
19 | Layout/ClosingParenthesisIndentation:
20 | Exclude:
21 | - 'spec/api_error_handler/serializers/xml_spec.rb'
22 |
23 | # Offense count: 2
24 | # Configuration parameters: Max.
25 | Metrics/AbcSize:
26 | Exclude:
27 | - 'lib/api_error_handler.rb'
28 | - 'lib/api_error_handler/error_reporter.rb'
29 |
30 | # Offense count: 1
31 | # Configuration parameters: Max.
32 | Metrics/CyclomaticComplexity:
33 | Exclude:
34 | - 'lib/api_error_handler/error_reporter.rb'
35 |
36 | # Offense count: 3
37 | # Configuration parameters: CountComments, Max, ExcludedMethods.
38 | Metrics/MethodLength:
39 | Exclude:
40 | - 'lib/api_error_handler.rb'
41 | - 'lib/api_error_handler/error_reporter.rb'
42 | - 'lib/api_error_handler/error_id_generator.rb'
43 | - 'lib/api_error_handler/serializers/json_api.rb'
44 |
45 | # Offense count: 1
46 | # Configuration parameters: Max.
47 | Metrics/PerceivedComplexity:
48 | Exclude:
49 | - 'lib/api_error_handler/error_reporter.rb'
50 |
51 | # Offense count: 2
52 | # Cop supports --auto-correct.
53 | Style/ExpandPathArguments:
54 | Exclude:
55 | - 'api_error_handler.gemspec'
56 |
57 | # Offense count: 4
58 | # Cop supports --auto-correct.
59 | # Configuration parameters: EnforcedStyle.
60 | # SupportedStyles: implicit, explicit
61 | Style/RescueStandardError:
62 | Exclude:
63 | - 'lib/api_error_handler.rb'
64 | - 'spec/api_error_handler/serializers/json_api_spec.rb'
65 | - 'spec/api_error_handler/serializers/json_spec.rb'
66 | - 'spec/api_error_handler/serializers/xml_spec.rb'
67 |
68 | # Offense count: 2
69 | # Cop supports --auto-correct.
70 | # Configuration parameters: EnforcedStyleForMultiline.
71 | # SupportedStylesForMultiline: comma, consistent_comma, no_comma
72 | Style/TrailingCommaInArrayLiteral:
73 | Exclude:
74 | - 'lib/api_error_handler/serializers/json_api.rb'
75 | - 'spec/api_error_handler/serializers/json_api_spec.rb'
76 |
77 | # Offense count: 3
78 | # Cop supports --auto-correct.
79 | # Configuration parameters: EnforcedStyleForMultiline.
80 | # SupportedStylesForMultiline: comma, consistent_comma, no_comma
81 | Style/TrailingCommaInHashLiteral:
82 | Exclude:
83 | - 'lib/api_error_handler.rb'
84 | - 'lib/api_error_handler/serializers/json.rb'
85 | - 'lib/api_error_handler/serializers/json_api.rb'
86 |
--------------------------------------------------------------------------------
/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.3.8
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | ---
2 | language: ruby
3 | before_install:
4 | - gem update --system
5 | - gem install bundler
6 | install: bundle install --jobs=3 --retry=3
7 | cache: bundler
8 | branches:
9 | only:
10 | - master
11 | jobs:
12 | include:
13 | - rvm: 2.5.1
14 | gemfile: ./rails_5_test_app/Gemfile
15 | script: cd rails_5_test_app && bundle exec rspec
16 | - rvm: 2.5.1
17 | gemfile: ./rails_6_test_app/Gemfile
18 | script: cd rails_6_test_app && bundle exec rspec
19 | - rvm: 2.7.2
20 | gemfile: ./rails_6_test_app/Gemfile
21 | script: cd rails_6_test_app && bundle exec rspec
22 | - rvm: 3.0.0
23 | gemfile: ./rails_6_test_app/Gemfile
24 | script: cd rails_6_test_app && bundle exec rspec
25 | - rvm: 2.7.2
26 | gemfile: Gemfile
27 | script: bundle exec rubocop
28 | - rvm: 2.7.2
29 | gemfile: Gemfile
30 | script: bundle exec rspec
31 | - rvm: 3.0.0
32 | gemfile: Gemfile
33 | script: bundle exec rubocop
34 | - rvm: 3.0.0
35 | gemfile: Gemfile
36 | script: bundle exec rspec
37 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | source "https://rubygems.org"
4 |
5 | # Specify your gem's dependencies in api_error_handler.gemspec
6 | gemspec
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2019 James Stonehill
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ApiErrorHandler
2 | [](https://travis-ci.org/jamesstonehill/api_error_handler)
3 |
4 | Are your API error responses not all that you want them to be? If so, you've
5 | found the right gem! `api_error_handler` handles all aspects of returning
6 | informative, spec-compliant responses to clients when your application
7 | encounters an error in the course of processing a response.
8 |
9 | This "handling" includes:
10 | - __Error serialization__: each response will include a response body that
11 | gives some information on the type of error that your application
12 | encountered. See the [Responses Body Options](#response-body-options)
13 | section for details and configuration options.
14 | - __Status code setting__: `api_error_handler` will set the HTTP status code of
15 | the response based on the type of error that is raised. For example, when an
16 | `ActiveRecord::RecordNotFound` error is raised, it will set the response
17 | status to 404. See the [HTTP Status Mapping](#http-status-mapping) section
18 | for details and configuration options.
19 | - __Error reporting__: If you use a 3rd party bug tracking
20 | tool like Honeybadger or Sentry, `api_error_handler` will notify this
21 | service of the error for you so you don't have to!
22 | - __Content type setting__: `api_error_handler` will set the content type of the
23 | response based on the format of response body.
24 |
25 | ## Installation
26 |
27 | Add this line to your application's Gemfile:
28 |
29 | ```ruby
30 | gem 'api_error_handler'
31 | ```
32 |
33 | And then execute:
34 |
35 | $ bundle install
36 |
37 | ## Usage
38 |
39 | To get started, all you need to do is invoke `handle_api_errors` inside your
40 | controller like so:
41 |
42 | ```ruby
43 | class MyController < ActionController::API
44 | handle_api_errors()
45 |
46 | def index
47 | raise "Something is very very wrong!"
48 | end
49 | end
50 | ```
51 |
52 | Now when you go to `MyController#index`, your API will return the following
53 | response:
54 |
55 | ```json
56 | HTTP/1.1 500 Internal Server Error
57 | Content-Type: application/json
58 |
59 | {
60 | "error": {
61 | "title":"Internal Server Error",
62 | "detail":"Something is very very wrong!"
63 | }
64 | }
65 | ```
66 |
67 | ### Error handling options
68 |
69 | `handle_api_errors` implements a bunch of (hopefully) sensible defaults so that
70 | all you need to do is invoke `handle_api_errors()` in your controller to get
71 | useful error handling! However, in all likelihood you'll want to override some
72 | of these options. This section gives details on the various options available
73 | for configuring the `api_error_handler`.
74 |
75 | #### Response Body Options
76 | By default, `handle_api_errors` picks the `:json` format for serializing errors.
77 | However, this gem comes with a number of other formats for serializing your
78 | errors.
79 |
80 | ##### JSON (the default)
81 | ```ruby
82 | handle_api_errors(format: :json)
83 | # Or
84 | handle_api_errors()
85 | ```
86 |
87 | ```json
88 | HTTP/1.1 500 Internal Server Error
89 | Content-Type: application/json
90 |
91 | {
92 | "error": {
93 | "title":"Internal Server Error",
94 | "detail":"Something is very very wrong!"
95 | }
96 | }
97 | ```
98 |
99 | ##### JSON:API
100 | If your API follows the `JSON:API` spec, you'll want to use the `:json_api`
101 | format option.
102 |
103 | ```ruby
104 | handle_api_errors(format: :json_api)
105 | ```
106 |
107 | Responses with this format will follow the `JSON:API` [specification for error
108 | objects](https://jsonapi.org/format/#error-objects). This will look something
109 | like this:
110 |
111 | ```json
112 | HTTP/1.1 500 Internal Server Error
113 | Content-Type: application/vnd.api+json
114 |
115 | {
116 | "errors": [
117 | {
118 | "status":"500",
119 | "title":"Internal Server Error",
120 | "detail":"Something is very very wrong!"
121 | }
122 | ]
123 | }
124 | ```
125 |
126 | ##### XML
127 | ```ruby
128 | handle_api_errors(format: :xml)
129 | ```
130 |
131 | ```xml
132 |
133 |
134 | Internal Server Error
135 | Something is very very wrong!
136 |
137 | ```
138 |
139 | ##### Custom Error Responses
140 | If none of the out-of-the-box options suit you then you can pass in your own
141 | error serializer like so:
142 |
143 | ```ruby
144 | handle_api_errors(serializer: MyCustomErrorSerializer)
145 | ```
146 |
147 | The custom serializer must implement two instance methods, `serialize` and
148 | `render_format`. The `serialize` method should return the body of the response
149 | you want to render. The `render_format` should be the format that you want to
150 | render the response in (e.g `:json`, `:xml`, `:plain`), which will be passed to
151 | Rails' `render` method.
152 |
153 | It is recommended you inherit your serializer from
154 | `ApiErrorHandler::Serializers::BaseSerializer` to gain some helpful instance
155 | methods and defaults.
156 |
157 | ```ruby
158 | class MyCustomErrorSerializer < ApiErrorHandler::Serializers::BaseSerializer
159 | def serialize(serializer_options)
160 | # The `title` and `status_code` come from the BaseSerializer.
161 | "Error! Title: #{title} Status Code: #{status_code}"
162 | end
163 |
164 | def render_format
165 | :plain
166 | end
167 | end
168 | ```
169 | ##### Backtraces
170 | If you want to include the error's backtrace in the response body:
171 |
172 | ```ruby
173 | handle_api_errors(backtrace: true)
174 | ```
175 |
176 | ```json
177 | {
178 | "error": {
179 | "title":"Internal Server Error",
180 | "detail":"Something is very very wrong!",
181 | "backtrace": [
182 | # The backtrace
183 | ]
184 | }
185 | }
186 | ```
187 |
188 | ### HTTP Status Mapping
189 |
190 | Most of the time, you'll want to set the HTTP status code based on the type of
191 | error being raised. To determine which errors map to which status codes,
192 | `api_error_handler` uses `ActionDispatch::ExceptionWrapper.rescue_responses`. If
193 | you're using Rails with ActiveRecord, by default this includes:
194 |
195 | ```ruby
196 | {
197 | "ActionController::RoutingError" => :not_found,
198 | "AbstractController::ActionNotFound" => :not_found,
199 | "ActionController::MethodNotAllowed" => :method_not_allowed,
200 | "ActionController::UnknownHttpMethod" => :method_not_allowed,
201 | "ActionController::NotImplemented" => :not_implemented,
202 | "ActionController::UnknownFormat" => :not_acceptable,
203 | "Mime::Type::InvalidMimeType" => :not_acceptable,
204 | "ActionController::MissingExactTemplate" => :not_acceptable,
205 | "ActionController::InvalidAuthenticityToken" => :unprocessable_entity,
206 | "ActionController::InvalidCrossOriginRequest" => :unprocessable_entity,
207 | "ActionDispatch::Http::Parameters::ParseError" => :bad_request,
208 | "ActionController::BadRequest" => :bad_request,
209 | "ActionController::ParameterMissing" => :bad_request,
210 | "Rack::QueryParser::ParameterTypeError" => :bad_request,
211 | "Rack::QueryParser::InvalidParameterError" => :bad_request,
212 | "ActiveRecord::RecordNotFound" => :not_found,
213 | "ActiveRecord::StaleObjectError" => :conflict,
214 | "ActiveRecord::RecordInvalid" => :unprocessable_entity,
215 | "ActiveRecord::RecordNotSaved" => :unprocessable_entity
216 | }
217 | ```
218 | - https://guides.rubyonrails.org/configuring.html#configuring-action-dispatch
219 |
220 | You can add to this mapping on an application level by doing the following:
221 | ```ruby
222 | config.action_dispatch.rescue_responses.merge!(
223 | "AuthenticationError" => :unauthorized
224 | )
225 | ```
226 |
227 | Now when an you raise an `AuthenticationError` in one of your actions, the
228 | status code of the response will be 401.
229 |
230 | ### Error IDs
231 | Sometimes it's helpful to include IDs with your error responses so that you can
232 | correlate a specific error with a record in your logs or bug tracking software.
233 | For this you can use the `error_id` option.
234 |
235 | You can either use the UUID error strategy
236 | ```ruby
237 | handle_api_errors(error_id: :uuid)
238 | ```
239 |
240 | Or pass a Proc if you need to do something custom.
241 | ```ruby
242 | handle_api_errors(error_id: Proc.new { |error| SecureRandom.uuid })
243 | ```
244 |
245 | These will result in:
246 | ```json
247 | {
248 | "error": {
249 | "title": "Internal Server Error",
250 | "detail": "Something is very very wrong!",
251 | "id": "4ab520f2-ae33-4539-9371-ea21aada5582"
252 | }
253 | }
254 | ```
255 |
256 | ### Error Reporting
257 | If you use an external error tracking software like Sentry or Honeybadger, you'll
258 | want to report all errors to that service.
259 |
260 | #### Out of the Box Error Reporting
261 | There are a few supported error reporter options that you can select.
262 |
263 | ##### Raven/Sentry
264 | ```ruby
265 | handle_api_errors(error_reporter: :raven)
266 | # Or
267 | handle_api_errors(error_reporter: :sentry)
268 | ```
269 |
270 | ##### Honeybadger
271 | ```ruby
272 | handle_api_errors(error_reporter: :honeybadger)
273 | ```
274 |
275 | __NOTE:__ If you use the `:error_id` option, the error error reporter will tag
276 | the exception with the error ID when reporting the error.
277 |
278 | #### Custom Reporting
279 | If none of the out of the box options work for you, you can pass in a proc which
280 | will receive the error and the error_id as arguments.
281 |
282 | ```ruby
283 | handle_api_errors(
284 | error_reporter: Proc.new do |error, error_id|
285 | # Do something with the `error` here.
286 | end
287 | )
288 | ```
289 |
290 | ### Setting Content Type
291 | The api_error_handler will set the content type of your error based on the
292 | `format` option you pick. However, you can override this by setting the
293 | `content_type` option if you wish.
294 |
295 | ```ruby
296 | handle_api_errors(
297 | format: :json,
298 | content_type: 'application/vnd.api+json'
299 | )
300 | ```
301 |
302 | ```json
303 | HTTP/1.1 500 Internal Server Error
304 | Content-Type: application/vnd.api+json
305 |
306 | {
307 | "error": {
308 | "title":"Internal Server Error",
309 | "detail":"Something is very very wrong!"
310 | }
311 | }
312 | ```
313 |
314 | ## License
315 |
316 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
317 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "bundler/gem_tasks"
4 | require "rspec/core/rake_task"
5 |
6 | RSpec::Core::RakeTask.new(:spec)
7 |
8 | task default: :spec
9 |
--------------------------------------------------------------------------------
/api_error_handler.gemspec:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | lib = File.expand_path("../lib", __FILE__)
4 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5 | require "api_error_handler/version"
6 |
7 | Gem::Specification.new do |spec|
8 | spec.name = "api_error_handler"
9 | spec.version = ApiErrorHandler::VERSION
10 | spec.authors = ["James Stonehill"]
11 | spec.email = ["james.stonehill@gmail.com"]
12 | spec.required_ruby_version = ">= 2.5"
13 |
14 | spec.summary = <<~SUMMARY
15 | A gem that helps you easily handle exceptions in your Rails API and return
16 | informative responses to the client.
17 | SUMMARY
18 |
19 | spec.description = <<~DESCRIPTION
20 | A gem that helps you easily handle exceptions in your Ruby on Rails API and
21 | return informative responses to the client by serializing exceptions into JSON
22 | and other popular API formats and returning a response with a status code that
23 | makes sense based on the exception.
24 | DESCRIPTION
25 |
26 | spec.homepage = "https://github.com/jamesstonehill/api_error_handler"
27 | spec.license = "MIT"
28 |
29 | # Specify which files should be added to the gem when it is released.
30 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
31 | spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
32 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|rails_.+)/}) }
33 | end
34 | spec.bindir = "exe"
35 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
36 | spec.require_paths = ["lib"]
37 |
38 | spec.add_dependency "activesupport", ">= 5.0"
39 | spec.add_dependency "actionpack", ">= 5.0"
40 | spec.add_dependency "rack", ">= 1.0"
41 |
42 | spec.add_development_dependency "bundler", "~> 2.0"
43 | spec.add_development_dependency "rake", "~> 13.0"
44 | spec.add_development_dependency "rspec-rails", "~> 3.9"
45 | spec.add_development_dependency "rubocop", "~> 0.80.0"
46 | spec.add_development_dependency "pry-byebug"
47 | end
48 |
--------------------------------------------------------------------------------
/bin/console:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 |
4 | require "bundler/setup"
5 | require "api_error_handler"
6 |
7 | # You can add fixtures and/or initialization code here to make experimenting
8 | # with your gem easier. You can also use a different console, if you like.
9 |
10 | # (If you use this, don't forget to add pry to your Gemfile!)
11 | # require "pry"
12 | # Pry.start
13 |
14 | require "irb"
15 | IRB.start(__FILE__)
16 |
--------------------------------------------------------------------------------
/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 | IFS=$'\n\t'
4 | set -vx
5 |
6 | bundle install
7 |
8 | # Do any other automated setup that you need to do here
9 |
--------------------------------------------------------------------------------
/lib/api_error_handler.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "./api_error_handler/version"
4 | require_relative "./api_error_handler/action_controller"
5 | require_relative "./api_error_handler/error_id_generator"
6 | require_relative "./api_error_handler/error_reporter"
7 | Dir[File.join(__dir__, "api_error_handler", "serializers", "*.rb")].sort.each do |file|
8 | require file
9 | end
10 |
11 | module ApiErrorHandler
12 | SERIALIZERS_BY_FORMAT = {
13 | json: Serializers::Json,
14 | json_api: Serializers::JsonApi,
15 | xml: Serializers::Xml,
16 | }.freeze
17 |
18 | SERIALIZER_OPTIONS = {
19 | backtrace: false,
20 | }.freeze
21 |
22 | CONTENT_TYPE_BY_FORMAT = {
23 | json_api: "application/vnd.api+json"
24 | }.freeze
25 |
26 | def handle_api_errors(options = {})
27 | format = options.fetch(:format, :json)
28 | error_reporter = ErrorReporter.new(options[:error_reporter])
29 | serializer_options = SERIALIZER_OPTIONS.merge(
30 | options.slice(*SERIALIZER_OPTIONS.keys)
31 | )
32 |
33 | serializer_class = options[:serializer] || SERIALIZERS_BY_FORMAT.fetch(format)
34 | content_type = options[:content_type] || CONTENT_TYPE_BY_FORMAT[format]
35 | rescue_from StandardError do |error|
36 | status = ActionDispatch::ExceptionWrapper.rescue_responses[error.class.to_s]
37 |
38 | error_id = ErrorIdGenerator.run(options[:error_id])
39 | error_reporter.report(error, error_id: error_id)
40 |
41 | serializer = serializer_class.new(error, status)
42 | response_body = serializer.serialize(
43 | serializer_options.merge(error_id: error_id)
44 | )
45 |
46 | render(
47 | serializer.render_format => response_body,
48 | content_type: content_type,
49 | status: status
50 | )
51 | rescue
52 | raise error
53 | end
54 | end
55 | end
56 |
--------------------------------------------------------------------------------
/lib/api_error_handler/action_controller.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "active_support/lazy_load_hooks"
4 | require "action_controller"
5 |
6 | ActiveSupport.on_load :action_controller do
7 | ::ActionController::Base.extend ApiErrorHandler
8 | ::ActionController::API.extend ApiErrorHandler
9 | end
10 |
--------------------------------------------------------------------------------
/lib/api_error_handler/error_id_generator.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "securerandom"
4 | require_relative "./errors"
5 |
6 | module ApiErrorHandler
7 | class ErrorIdGenerator
8 | def self.run(error_id_option)
9 | if error_id_option.instance_of?(Proc)
10 | error_id_option.call
11 | elsif error_id_option == :uuid
12 | SecureRandom.uuid
13 | elsif error_id_option.nil?
14 | nil
15 | else
16 | raise(
17 | InvalidOptionError,
18 | "Unable to handle `#{error_id_option}` as argument for the `:error_id` option."
19 | )
20 | end
21 | end
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/lib/api_error_handler/error_reporter.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "logger"
4 | require_relative "./errors"
5 |
6 | module ApiErrorHandler
7 | class ErrorReporter
8 | def initialize(strategy)
9 | @strategy = strategy
10 | end
11 |
12 | def report(error, error_id: nil)
13 | if @strategy.nil?
14 | true
15 | elsif @strategy.instance_of?(Proc)
16 | @strategy.call(error, error_id)
17 | elsif @strategy == :honeybadger
18 | raise_dependency_error(missing_constant: "Honeybadger") unless defined?(Honeybadger)
19 |
20 | context = error_id ? { error_id: error_id } : {}
21 | Honeybadger.notify(error, context: context)
22 | elsif @strategy == :raven
23 | raise_dependency_error(missing_constant: "Raven") unless defined?(Raven)
24 |
25 | extra = error_id ? { error_id: error_id } : {}
26 | Raven.capture_exception(error, extra: extra)
27 | elsif @strategy == :sentry
28 | raise_dependency_error(missing_constant: "Sentry") unless defined?(Sentry)
29 |
30 | extra = error_id ? { error_id: error_id } : {}
31 | Sentry.capture_exception(error, extra: extra)
32 | else
33 | raise(
34 | InvalidOptionError,
35 | "`#{@strategy.inspect}` is an invalid argument for the `:error_id` option."
36 | )
37 | end
38 | end
39 |
40 | private
41 |
42 | def raise_dependency_error(missing_constant:)
43 | raise MissingDependencyError, <<~MESSAGE
44 | You selected the #{@strategy.inspect} error reporter option but the
45 | #{missing_constant} constant is not defined. If you wish to use this
46 | error reporting option you must have the #{@strategy} client gem
47 | installed.
48 | MESSAGE
49 | end
50 | end
51 | end
52 |
--------------------------------------------------------------------------------
/lib/api_error_handler/errors.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module ApiErrorHandler
4 | class Error < StandardError; end
5 |
6 | class InvalidOptionError < Error; end
7 | class MissingDependencyError < Error; end
8 | end
9 |
--------------------------------------------------------------------------------
/lib/api_error_handler/serializers/base_serializer.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "rack/utils"
4 |
5 | module ApiErrorHandler
6 | module Serializers
7 | class BaseSerializer
8 | DEFAULT_STATUS_CODE = "500"
9 |
10 | def initialize(error, status)
11 | @error = error
12 | @status = status
13 | end
14 |
15 | def status_code
16 | Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(@status, DEFAULT_STATUS_CODE).to_s
17 | end
18 |
19 | def title
20 | Rack::Utils::HTTP_STATUS_CODES.fetch(status_code.to_i)
21 | end
22 | end
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/lib/api_error_handler/serializers/json.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "./base_serializer"
4 |
5 | module ApiErrorHandler
6 | module Serializers
7 | class Json < BaseSerializer
8 | # There is no official spec that governs this error response format so
9 | # this serializer is just trying to impliment a simple response with
10 | # sensible defaults.
11 | #
12 | # I borrowed heavily from Facebook's error response format since it seems
13 | # to be a reasonable approach for a simple light-weight error response.
14 |
15 | def serialize(options = {})
16 | body = {
17 | error: {
18 | title: title,
19 | detail: @error.message,
20 | }
21 | }
22 |
23 | body[:error][:id] = options[:error_id] if options[:error_id]
24 | body[:error][:backtrace] = @error.backtrace if options[:backtrace]
25 |
26 | body.to_json
27 | end
28 |
29 | def render_format
30 | :json
31 | end
32 | end
33 | end
34 | end
35 |
--------------------------------------------------------------------------------
/lib/api_error_handler/serializers/json_api.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "./base_serializer"
4 |
5 | module ApiErrorHandler
6 | module Serializers
7 | class JsonApi < BaseSerializer
8 | def serialize(options = {})
9 | body = {
10 | errors: [
11 | {
12 | status: status_code,
13 | title: title,
14 | detail: @error.message,
15 | }
16 | ]
17 | }
18 |
19 | body[:errors].first[:id] = options[:error_id] if options[:error_id]
20 | body[:errors].first[:meta] = { backtrace: @error.backtrace } if options[:backtrace]
21 |
22 | body.to_json
23 | end
24 |
25 | def render_format
26 | :json
27 | end
28 | end
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/lib/api_error_handler/serializers/xml.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "active_support/core_ext/hash/conversions"
4 | require_relative "./base_serializer"
5 |
6 | module ApiErrorHandler
7 | module Serializers
8 | class Xml < BaseSerializer
9 | def serialize(options = {})
10 | body = {
11 | Title: title,
12 | Detail: @error.message,
13 | }
14 |
15 | body[:Id] = options[:error_id] if options[:error_id]
16 | body[:Backtrace] = @error.backtrace if options[:backtrace]
17 |
18 | body.to_xml(root: "Error")
19 | end
20 |
21 | def render_format
22 | :xml
23 | end
24 | end
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/lib/api_error_handler/version.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module ApiErrorHandler
4 | VERSION = "0.2.1"
5 | end
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/.rspec:
--------------------------------------------------------------------------------
1 | --require spec_helper
2 |
--------------------------------------------------------------------------------
/rails_5_test_app/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" }
3 |
4 | ruby '2.5.1'
5 |
6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
7 | gem 'rails', '~> 5.2.5'
8 | # Use sqlite3 as the database for Active Record
9 | gem 'sqlite3'
10 | # Use Puma as the app server
11 | gem 'puma', '~> 3.11'
12 | # Use SCSS for stylesheets
13 | # gem 'sass-rails', '~> 5.0'
14 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
15 | gem 'jbuilder', '~> 2.5'
16 | # Use Redis adapter to run Action Cable in production
17 | # gem 'redis', '~> 4.0'
18 | # Use ActiveModel has_secure_password
19 | # gem 'bcrypt', '~> 3.1.7'
20 |
21 | # Use ActiveStorage variant
22 | # gem 'mini_magick', '~> 4.8'
23 |
24 | # Use Capistrano for deployment
25 | # gem 'capistrano-rails', group: :development
26 |
27 | # Reduces boot times through caching; required in config/boot.rb
28 | gem 'bootsnap', '>= 1.1.0', require: false
29 |
30 | gem 'api_error_handler', path: ".."
31 |
32 | group :development, :test do
33 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console
34 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
35 | gem 'rspec-rails', '~> 3.8.2'
36 | end
37 |
38 | group :development do
39 | # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
40 | gem 'web-console', '>= 3.3.0'
41 | gem 'listen', '>= 3.0.5', '< 3.2'
42 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
43 | gem 'spring'
44 | gem 'spring-watcher-listen', '~> 2.0.0'
45 | end
46 |
47 | group :test do
48 | # Adds support for Capybara system testing and selenium driver
49 | # gem 'capybara', '>= 2.15'
50 | # gem 'selenium-webdriver'
51 | # Easy installation and use of chromedriver to run system tests with Chrome
52 | # gem 'chromedriver-helper'
53 | end
54 |
55 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
56 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
57 |
--------------------------------------------------------------------------------
/rails_5_test_app/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: ..
3 | specs:
4 | api_error_handler (0.2.0)
5 | actionpack (>= 5.0)
6 | activesupport (>= 5.0)
7 | rack (>= 1.0)
8 |
9 | GEM
10 | remote: https://rubygems.org/
11 | specs:
12 | actioncable (5.2.5)
13 | actionpack (= 5.2.5)
14 | nio4r (~> 2.0)
15 | websocket-driver (>= 0.6.1)
16 | actionmailer (5.2.5)
17 | actionpack (= 5.2.5)
18 | actionview (= 5.2.5)
19 | activejob (= 5.2.5)
20 | mail (~> 2.5, >= 2.5.4)
21 | rails-dom-testing (~> 2.0)
22 | actionpack (5.2.5)
23 | actionview (= 5.2.5)
24 | activesupport (= 5.2.5)
25 | rack (~> 2.0, >= 2.0.8)
26 | rack-test (>= 0.6.3)
27 | rails-dom-testing (~> 2.0)
28 | rails-html-sanitizer (~> 1.0, >= 1.0.2)
29 | actionview (5.2.5)
30 | activesupport (= 5.2.5)
31 | builder (~> 3.1)
32 | erubi (~> 1.4)
33 | rails-dom-testing (~> 2.0)
34 | rails-html-sanitizer (~> 1.0, >= 1.0.3)
35 | activejob (5.2.5)
36 | activesupport (= 5.2.5)
37 | globalid (>= 0.3.6)
38 | activemodel (5.2.5)
39 | activesupport (= 5.2.5)
40 | activerecord (5.2.5)
41 | activemodel (= 5.2.5)
42 | activesupport (= 5.2.5)
43 | arel (>= 9.0)
44 | activestorage (5.2.5)
45 | actionpack (= 5.2.5)
46 | activerecord (= 5.2.5)
47 | marcel (~> 1.0.0)
48 | activesupport (5.2.5)
49 | concurrent-ruby (~> 1.0, >= 1.0.2)
50 | i18n (>= 0.7, < 2)
51 | minitest (~> 5.1)
52 | tzinfo (~> 1.1)
53 | arel (9.0.0)
54 | bindex (0.8.1)
55 | bootsnap (1.7.3)
56 | msgpack (~> 1.0)
57 | builder (3.2.4)
58 | byebug (11.1.3)
59 | concurrent-ruby (1.1.8)
60 | crass (1.0.6)
61 | diff-lcs (1.4.4)
62 | erubi (1.10.0)
63 | ffi (1.15.0)
64 | globalid (0.4.2)
65 | activesupport (>= 4.2.0)
66 | i18n (1.8.10)
67 | concurrent-ruby (~> 1.0)
68 | jbuilder (2.11.2)
69 | activesupport (>= 5.0.0)
70 | listen (3.1.5)
71 | rb-fsevent (~> 0.9, >= 0.9.4)
72 | rb-inotify (~> 0.9, >= 0.9.7)
73 | ruby_dep (~> 1.2)
74 | loofah (2.9.0)
75 | crass (~> 1.0.2)
76 | nokogiri (>= 1.5.9)
77 | mail (2.7.1)
78 | mini_mime (>= 0.1.1)
79 | marcel (1.0.1)
80 | method_source (1.0.0)
81 | mini_mime (1.1.0)
82 | mini_portile2 (2.5.0)
83 | minitest (5.14.4)
84 | msgpack (1.4.2)
85 | nio4r (2.5.7)
86 | nokogiri (1.11.2)
87 | mini_portile2 (~> 2.5.0)
88 | racc (~> 1.4)
89 | puma (3.12.6)
90 | racc (1.5.2)
91 | rack (2.2.3)
92 | rack-test (1.1.0)
93 | rack (>= 1.0, < 3)
94 | rails (5.2.5)
95 | actioncable (= 5.2.5)
96 | actionmailer (= 5.2.5)
97 | actionpack (= 5.2.5)
98 | actionview (= 5.2.5)
99 | activejob (= 5.2.5)
100 | activemodel (= 5.2.5)
101 | activerecord (= 5.2.5)
102 | activestorage (= 5.2.5)
103 | activesupport (= 5.2.5)
104 | bundler (>= 1.3.0)
105 | railties (= 5.2.5)
106 | sprockets-rails (>= 2.0.0)
107 | rails-dom-testing (2.0.3)
108 | activesupport (>= 4.2.0)
109 | nokogiri (>= 1.6)
110 | rails-html-sanitizer (1.3.0)
111 | loofah (~> 2.3)
112 | railties (5.2.5)
113 | actionpack (= 5.2.5)
114 | activesupport (= 5.2.5)
115 | method_source
116 | rake (>= 0.8.7)
117 | thor (>= 0.19.0, < 2.0)
118 | rake (13.0.3)
119 | rb-fsevent (0.10.4)
120 | rb-inotify (0.10.1)
121 | ffi (~> 1.0)
122 | rspec-core (3.8.2)
123 | rspec-support (~> 3.8.0)
124 | rspec-expectations (3.8.6)
125 | diff-lcs (>= 1.2.0, < 2.0)
126 | rspec-support (~> 3.8.0)
127 | rspec-mocks (3.8.2)
128 | diff-lcs (>= 1.2.0, < 2.0)
129 | rspec-support (~> 3.8.0)
130 | rspec-rails (3.8.3)
131 | actionpack (>= 3.0)
132 | activesupport (>= 3.0)
133 | railties (>= 3.0)
134 | rspec-core (~> 3.8.0)
135 | rspec-expectations (~> 3.8.0)
136 | rspec-mocks (~> 3.8.0)
137 | rspec-support (~> 3.8.0)
138 | rspec-support (3.8.3)
139 | ruby_dep (1.5.0)
140 | spring (2.1.1)
141 | spring-watcher-listen (2.0.1)
142 | listen (>= 2.7, < 4.0)
143 | spring (>= 1.2, < 3.0)
144 | sprockets (4.0.2)
145 | concurrent-ruby (~> 1.0)
146 | rack (> 1, < 3)
147 | sprockets-rails (3.2.2)
148 | actionpack (>= 4.0)
149 | activesupport (>= 4.0)
150 | sprockets (>= 3.0.0)
151 | sqlite3 (1.4.2)
152 | thor (1.1.0)
153 | thread_safe (0.3.6)
154 | tzinfo (1.2.9)
155 | thread_safe (~> 0.1)
156 | web-console (3.7.0)
157 | actionview (>= 5.0)
158 | activemodel (>= 5.0)
159 | bindex (>= 0.4.0)
160 | railties (>= 5.0)
161 | websocket-driver (0.7.3)
162 | websocket-extensions (>= 0.1.0)
163 | websocket-extensions (0.1.5)
164 |
165 | PLATFORMS
166 | ruby
167 |
168 | DEPENDENCIES
169 | api_error_handler!
170 | bootsnap (>= 1.1.0)
171 | byebug
172 | jbuilder (~> 2.5)
173 | listen (>= 3.0.5, < 3.2)
174 | puma (~> 3.11)
175 | rails (~> 5.2.5)
176 | rspec-rails (~> 3.8.2)
177 | spring
178 | spring-watcher-listen (~> 2.0.0)
179 | sqlite3
180 | tzinfo-data
181 | web-console (>= 3.3.0)
182 |
183 | RUBY VERSION
184 | ruby 2.5.1p57
185 |
186 | BUNDLED WITH
187 | 2.2.15
188 |
--------------------------------------------------------------------------------
/rails_5_test_app/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require_relative 'config/application'
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/assets/config/manifest.js:
--------------------------------------------------------------------------------
1 | //= link_tree ../images
2 | //= link_directory ../stylesheets .css
3 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/assets/images/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/app/assets/images/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
6 | * vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10 | * files in this directory. Styles in this file should be added after the last require_* statement.
11 | * It is generally better to create a new file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/channels/application_cable/channel.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Channel < ActionCable::Channel::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/channels/application_cable/connection.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Connection < ActionCable::Connection::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/controllers/api_controller.rb:
--------------------------------------------------------------------------------
1 | class ApiController < ActionController::API
2 | end
3 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | end
3 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/app/controllers/concerns/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/app/controllers/tests_controller.rb:
--------------------------------------------------------------------------------
1 | class TestsController < ApiController
2 | handle_api_errors()
3 |
4 | def runtime_error
5 | raise RuntimeError, "This is a RuntimeError!"
6 | end
7 |
8 | def record_not_found
9 | raise ActiveRecord::RecordNotFound, "Not found!"
10 | end
11 |
12 | def not_implemented
13 | raise ActionController::NotImplemented, "Not Implemented!"
14 | end
15 |
16 | def custom_auth_error
17 | # `config.action_dispatch.rescue_responses` has been altered to map this
18 | # error to the :unauthorized status code in config/application.rb
19 | raise CustomAuthError, "Custom authentication error!"
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/errors/custom_auth_error.rb:
--------------------------------------------------------------------------------
1 | class CustomAuthError < StandardError; end
2 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/jobs/application_job.rb:
--------------------------------------------------------------------------------
1 | class ApplicationJob < ActiveJob::Base
2 | end
3 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/mailers/application_mailer.rb:
--------------------------------------------------------------------------------
1 | class ApplicationMailer < ActionMailer::Base
2 | default from: 'from@example.com'
3 | layout 'mailer'
4 | end
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/models/application_record.rb:
--------------------------------------------------------------------------------
1 | class ApplicationRecord < ActiveRecord::Base
2 | self.abstract_class = true
3 | end
4 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/models/concerns/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/app/models/concerns/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | TestApp
5 | <%= csrf_meta_tags %>
6 | <%= csp_meta_tag %>
7 |
8 | <%= stylesheet_link_tag 'application', media: 'all' %>
9 |
10 |
11 |
12 | <%= yield %>
13 |
14 |
15 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/views/layouts/mailer.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
--------------------------------------------------------------------------------
/rails_5_test_app/app/views/layouts/mailer.text.erb:
--------------------------------------------------------------------------------
1 | <%= yield %>
2 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
3 | load Gem.bin_path('bundler', 'bundle')
4 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | APP_PATH = File.expand_path('../config/application', __dir__)
8 | require_relative '../config/boot'
9 | require 'rails/commands'
10 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | require_relative '../config/boot'
8 | require 'rake'
9 | Rake.application.run
10 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'fileutils'
3 | include FileUtils
4 |
5 | # path to your application root.
6 | APP_ROOT = File.expand_path('..', __dir__)
7 |
8 | def system!(*args)
9 | system(*args) || abort("\n== Command #{args} failed ==")
10 | end
11 |
12 | chdir APP_ROOT do
13 | # This script is a starting point to setup your application.
14 | # Add necessary setup steps to this file.
15 |
16 | puts '== Installing dependencies =='
17 | system! 'gem install bundler --conservative'
18 | system('bundle check') || system!('bundle install')
19 |
20 | # Install JavaScript dependencies if using Yarn
21 | # system('bin/yarn')
22 |
23 | # puts "\n== Copying sample files =="
24 | # unless File.exist?('config/database.yml')
25 | # cp 'config/database.yml.sample', 'config/database.yml'
26 | # end
27 |
28 | puts "\n== Preparing database =="
29 | system! 'bin/rails db:setup'
30 |
31 | puts "\n== Removing old logs and tempfiles =="
32 | system! 'bin/rails log:clear tmp:clear'
33 |
34 | puts "\n== Restarting application server =="
35 | system! 'bin/rails restart'
36 | end
37 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/spring:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | # This file loads Spring without using Bundler, in order to be fast.
4 | # It gets overwritten when you run the `spring binstub` command.
5 |
6 | unless defined?(Spring)
7 | require 'rubygems'
8 | require 'bundler'
9 |
10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
11 | spring = lockfile.specs.detect { |spec| spec.name == 'spring' }
12 | if spring
13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
14 | gem 'spring', spring.version
15 | require 'spring/binstub'
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/update:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'fileutils'
3 | include FileUtils
4 |
5 | # path to your application root.
6 | APP_ROOT = File.expand_path('..', __dir__)
7 |
8 | def system!(*args)
9 | system(*args) || abort("\n== Command #{args} failed ==")
10 | end
11 |
12 | chdir APP_ROOT do
13 | # This script is a way to update your development environment automatically.
14 | # Add necessary update steps to this file.
15 |
16 | puts '== Installing dependencies =='
17 | system! 'gem install bundler --conservative'
18 | system('bundle check') || system!('bundle install')
19 |
20 | # Install JavaScript dependencies if using Yarn
21 | # system('bin/yarn')
22 |
23 | puts "\n== Updating database =="
24 | system! 'bin/rails db:migrate'
25 |
26 | puts "\n== Removing old logs and tempfiles =="
27 | system! 'bin/rails log:clear tmp:clear'
28 |
29 | puts "\n== Restarting application server =="
30 | system! 'bin/rails restart'
31 | end
32 |
--------------------------------------------------------------------------------
/rails_5_test_app/bin/yarn:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | APP_ROOT = File.expand_path('..', __dir__)
3 | Dir.chdir(APP_ROOT) do
4 | begin
5 | exec "yarnpkg", *ARGV
6 | rescue Errno::ENOENT
7 | $stderr.puts "Yarn executable was not detected in the system."
8 | $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install"
9 | exit 1
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/rails_5_test_app/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require_relative 'config/environment'
4 |
5 | run Rails.application
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative 'boot'
2 |
3 | require 'rails/all'
4 |
5 | # Require the gems listed in Gemfile, including any gems
6 | # you've limited to :test, :development, or :production.
7 | Bundler.require(*Rails.groups)
8 |
9 | module TestApp
10 | class Application < Rails::Application
11 | # Initialize configuration defaults for originally generated Rails version.
12 | config.load_defaults 5.2
13 |
14 | # Settings in config/environments/* take precedence over those specified here.
15 | # Application configuration can go into files in config/initializers
16 | # -- all .rb files in that directory are automatically loaded after loading
17 | # the framework and any gems in your application.
18 |
19 | config.action_dispatch.rescue_responses.merge!(
20 | "CustomAuthError" => :unauthorized
21 | )
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/boot.rb:
--------------------------------------------------------------------------------
1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
2 |
3 | require 'bundler/setup' # Set up gems listed in the Gemfile.
4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/cable.yml:
--------------------------------------------------------------------------------
1 | development:
2 | adapter: async
3 |
4 | test:
5 | adapter: async
6 |
7 | production:
8 | adapter: redis
9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
10 | channel_prefix: test_app_production
11 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/credentials.yml.enc:
--------------------------------------------------------------------------------
1 | FFzcxJTc3JSt5rS+4v1ivDHks3/ryDLPga/uNIBUaI5ue3fFodxONbaWfjJ3ZuUOzpQwvBh4PSeYC/VUAN/2air6cu2VK8DtV9Lh9XIAd38Q78HPfiC7BQEQPxxhT/VqHgG8OPIqJv1MmsUP8ZdntokfG7RUOIYdoqiyzTD3/vWCNhtd5rwejVT3R30stUVvgbQPmLS8Q31+s+ItQWQEHzG6EWQ5mXu8CUay6xkJWA0ahh72NLA2IwoUJpoFc3XmvpNRbc6q+rgH/SEaASIgrmAbR0XdVrxNfs3pu9PTj/sbTscBHq8f76NP2fwqXFiTYa3q30NsAzzEE5VCbEIEe/RU6jispgIvrhwxMB2zajYnh7mJcO+D1kiPESE0ogRrxNmIPYsZsLh8BUKIKPZdMur7o4XSTs5jgEmG--fb+d5ZE55WCJdjdd--XxkKhmT20vPZFdeyryHplQ==
--------------------------------------------------------------------------------
/rails_5_test_app/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite version 3.x
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: sqlite3
9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: ":memory:"
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: ":memory:"
22 |
23 | production:
24 | <<: *default
25 | database: ":memory:"
26 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative 'application'
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # In the development environment your application's code is reloaded on
5 | # every request. This slows down response time but is perfect for development
6 | # since you don't have to restart the web server when you make code changes.
7 | config.cache_classes = false
8 |
9 | # Do not eager load code on boot.
10 | config.eager_load = false
11 |
12 | # Show full error reports.
13 | config.consider_all_requests_local = true
14 |
15 | # Enable/disable caching. By default caching is disabled.
16 | # Run rails dev:cache to toggle caching.
17 | if Rails.root.join('tmp', 'caching-dev.txt').exist?
18 | config.action_controller.perform_caching = true
19 |
20 | config.cache_store = :memory_store
21 | config.public_file_server.headers = {
22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}"
23 | }
24 | else
25 | config.action_controller.perform_caching = false
26 |
27 | config.cache_store = :null_store
28 | end
29 |
30 | # Store uploaded files on the local file system (see config/storage.yml for options)
31 | config.active_storage.service = :local
32 |
33 | # Don't care if the mailer can't send.
34 | config.action_mailer.raise_delivery_errors = false
35 |
36 | config.action_mailer.perform_caching = false
37 |
38 | # Print deprecation notices to the Rails logger.
39 | config.active_support.deprecation = :log
40 |
41 | # Raise an error on page load if there are pending migrations.
42 | config.active_record.migration_error = :page_load
43 |
44 | # Highlight code that triggered database queries in logs.
45 | config.active_record.verbose_query_logs = true
46 |
47 | # Debug mode disables concatenation and preprocessing of assets.
48 | # This option may cause significant delays in view rendering with a large
49 | # number of complex assets.
50 | config.assets.debug = true
51 |
52 | # Suppress logger output for asset requests.
53 | config.assets.quiet = true
54 |
55 | # Raises error for missing translations
56 | # config.action_view.raise_on_missing_translations = true
57 |
58 | # Use an evented file watcher to asynchronously detect changes in source code,
59 | # routes, locales, etc. This feature depends on the listen gem.
60 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker
61 | end
62 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # Code is not reloaded between requests.
5 | config.cache_classes = true
6 |
7 | # Eager load code on boot. This eager loads most of Rails and
8 | # your application in memory, allowing both threaded web servers
9 | # and those relying on copy on write to perform better.
10 | # Rake tasks automatically ignore this option for performance.
11 | config.eager_load = true
12 |
13 | # Full error reports are disabled and caching is turned on.
14 | config.consider_all_requests_local = false
15 | config.action_controller.perform_caching = true
16 |
17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
19 | # config.require_master_key = true
20 |
21 | # Disable serving static files from the `/public` folder by default since
22 | # Apache or NGINX already handles this.
23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
24 |
25 | # Compress CSS.
26 | # config.assets.css_compressor = :sass
27 |
28 | # Do not fallback to assets pipeline if a precompiled asset is missed.
29 | config.assets.compile = false
30 |
31 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
32 |
33 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
34 | # config.action_controller.asset_host = 'http://assets.example.com'
35 |
36 | # Specifies the header that your server uses for sending files.
37 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
38 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
39 |
40 | # Store uploaded files on the local file system (see config/storage.yml for options)
41 | config.active_storage.service = :local
42 |
43 | # Mount Action Cable outside main process or domain
44 | # config.action_cable.mount_path = nil
45 | # config.action_cable.url = 'wss://example.com/cable'
46 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
47 |
48 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
49 | # config.force_ssl = true
50 |
51 | # Use the lowest log level to ensure availability of diagnostic information
52 | # when problems arise.
53 | config.log_level = :debug
54 |
55 | # Prepend all log lines with the following tags.
56 | config.log_tags = [ :request_id ]
57 |
58 | # Use a different cache store in production.
59 | # config.cache_store = :mem_cache_store
60 |
61 | # Use a real queuing backend for Active Job (and separate queues per environment)
62 | # config.active_job.queue_adapter = :resque
63 | # config.active_job.queue_name_prefix = "test_app_#{Rails.env}"
64 |
65 | config.action_mailer.perform_caching = false
66 |
67 | # Ignore bad email addresses and do not raise email delivery errors.
68 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
69 | # config.action_mailer.raise_delivery_errors = false
70 |
71 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
72 | # the I18n.default_locale when a translation cannot be found).
73 | config.i18n.fallbacks = true
74 |
75 | # Send deprecation notices to registered listeners.
76 | config.active_support.deprecation = :notify
77 |
78 | # Use default logging formatter so that PID and timestamp are not suppressed.
79 | config.log_formatter = ::Logger::Formatter.new
80 |
81 | # Use a different logger for distributed setups.
82 | # require 'syslog/logger'
83 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
84 |
85 | if ENV["RAILS_LOG_TO_STDOUT"].present?
86 | logger = ActiveSupport::Logger.new(STDOUT)
87 | logger.formatter = config.log_formatter
88 | config.logger = ActiveSupport::TaggedLogging.new(logger)
89 | end
90 |
91 | # Do not dump schema after migrations.
92 | config.active_record.dump_schema_after_migration = false
93 | end
94 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # The test environment is used exclusively to run your application's
5 | # test suite. You never need to work with it otherwise. Remember that
6 | # your test database is "scratch space" for the test suite and is wiped
7 | # and recreated between test runs. Don't rely on the data there!
8 | config.cache_classes = true
9 |
10 | # Do not eager load code on boot. This avoids loading your whole application
11 | # just for the purpose of running a single test. If you are using a tool that
12 | # preloads Rails for running tests, you may have to set it to true.
13 | config.eager_load = false
14 |
15 | # Configure public file server for tests with Cache-Control for performance.
16 | config.public_file_server.enabled = true
17 | config.public_file_server.headers = {
18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}"
19 | }
20 |
21 | # Show full error reports and disable caching.
22 | config.consider_all_requests_local = true
23 | config.action_controller.perform_caching = false
24 |
25 | # Raise exceptions instead of rendering exception templates.
26 | config.action_dispatch.show_exceptions = false
27 |
28 | # Disable request forgery protection in test environment.
29 | config.action_controller.allow_forgery_protection = false
30 |
31 | # Store uploaded files on the local file system in a temporary directory
32 | config.active_storage.service = :test
33 |
34 | config.action_mailer.perform_caching = false
35 |
36 | # Tell Action Mailer not to deliver emails to the real world.
37 | # The :test delivery method accumulates sent emails in the
38 | # ActionMailer::Base.deliveries array.
39 | config.action_mailer.delivery_method = :test
40 |
41 | # Print deprecation notices to the stderr.
42 | config.active_support.deprecation = :stderr
43 |
44 | # Raises error for missing translations
45 | # config.action_view.raise_on_missing_translations = true
46 | end
47 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ActiveSupport::Reloader.to_prepare do
4 | # ApplicationController.renderer.defaults.merge!(
5 | # http_host: 'example.org',
6 | # https: false
7 | # )
8 | # end
9 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = '1.0'
5 |
6 | # Add additional assets to the asset load path.
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 | # Add Yarn node_modules folder to the asset load path.
9 | Rails.application.config.assets.paths << Rails.root.join('node_modules')
10 |
11 | # Precompile additional assets.
12 | # application.js, application.css, and all non-JS/CSS in the app/assets
13 | # folder are already added.
14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css )
15 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/content_security_policy.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Define an application-wide content security policy
4 | # For further information see the following documentation
5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
6 |
7 | # Rails.application.config.content_security_policy do |policy|
8 | # policy.default_src :self, :https
9 | # policy.font_src :self, :https, :data
10 | # policy.img_src :self, :https, :data
11 | # policy.object_src :none
12 | # policy.script_src :self, :https
13 | # policy.style_src :self, :https
14 |
15 | # # Specify URI for violation reports
16 | # # policy.report_uri "/csp-violation-report-endpoint"
17 | # end
18 |
19 | # If you are using UJS then enable automatic nonce generation
20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
21 |
22 | # Report CSP violations to a specified URI
23 | # For further information see the following documentation:
24 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
25 | # Rails.application.config.content_security_policy_report_only = true
26 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # The following keys must be escaped otherwise they will not be retrieved by
20 | # the default I18n backend:
21 | #
22 | # true, false, on, off, yes, no
23 | #
24 | # Instead, surround them with single quotes.
25 | #
26 | # en:
27 | # 'true': 'foo'
28 | #
29 | # To learn more, please read the Rails Internationalization guide
30 | # available at http://guides.rubyonrails.org/i18n.html.
31 |
32 | en:
33 | hello: "Hello world"
34 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/master.key:
--------------------------------------------------------------------------------
1 | 68310befbc9eb5aa01c058494e78e984
--------------------------------------------------------------------------------
/rails_5_test_app/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers: a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum; this matches the default thread size of Active Record.
6 | #
7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
8 | threads threads_count, threads_count
9 |
10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000.
11 | #
12 | port ENV.fetch("PORT") { 3000 }
13 |
14 | # Specifies the `environment` that Puma will run in.
15 | #
16 | environment ENV.fetch("RAILS_ENV") { "development" }
17 |
18 | # Specifies the number of `workers` to boot in clustered mode.
19 | # Workers are forked webserver processes. If using threads and workers together
20 | # the concurrency of the application would be max `threads` * `workers`.
21 | # Workers do not work on JRuby or Windows (both of which do not support
22 | # processes).
23 | #
24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
25 |
26 | # Use the `preload_app!` method when specifying a `workers` number.
27 | # This directive tells Puma to first boot the application and load code
28 | # before forking the application. This takes advantage of Copy On Write
29 | # process behavior so workers use less memory.
30 | #
31 | # preload_app!
32 |
33 | # Allow puma to be restarted by `rails restart` command.
34 | plugin :tmp_restart
35 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
3 |
4 | get "/tests/runtime_error", controller: "tests"
5 | get "/tests/record_not_found", controller: "tests"
6 | get "/tests/not_implemented", controller: "tests"
7 | get "/tests/custom_auth_error", controller: "tests"
8 | end
9 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/spring.rb:
--------------------------------------------------------------------------------
1 | %w[
2 | .ruby-version
3 | .rbenv-vars
4 | tmp/restart.txt
5 | tmp/caching-dev.txt
6 | ].each { |path| Spring.watch(path) }
7 |
--------------------------------------------------------------------------------
/rails_5_test_app/config/storage.yml:
--------------------------------------------------------------------------------
1 | test:
2 | service: Disk
3 | root: <%= Rails.root.join("tmp/storage") %>
4 |
5 | local:
6 | service: Disk
7 | root: <%= Rails.root.join("storage") %>
8 |
9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
10 | # amazon:
11 | # service: S3
12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
14 | # region: us-east-1
15 | # bucket: your_own_bucket
16 |
17 | # Remember not to checkin your GCS keyfile to a repository
18 | # google:
19 | # service: GCS
20 | # project: your_project
21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
22 | # bucket: your_own_bucket
23 |
24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
25 | # microsoft:
26 | # service: AzureStorage
27 | # storage_account_name: your_account_name
28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
29 | # container: your_container_name
30 |
31 | # mirror:
32 | # service: Mirror
33 | # primary: local
34 | # mirrors: [ amazon, google, microsoft ]
35 |
--------------------------------------------------------------------------------
/rails_5_test_app/db/seeds.rb:
--------------------------------------------------------------------------------
1 | # This file should contain all the record creation needed to seed the database with its default values.
2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
3 | #
4 | # Examples:
5 | #
6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
7 | # Character.create(name: 'Luke', movie: movies.first)
8 |
--------------------------------------------------------------------------------
/rails_5_test_app/db/test.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/db/test.sqlite3
--------------------------------------------------------------------------------
/rails_5_test_app/lib/assets/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/lib/assets/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/lib/tasks/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/lib/tasks/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "test_app",
3 | "private": true,
4 | "dependencies": {}
5 | }
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/rails_5_test_app/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/rails_5_test_app/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/rails_5_test_app/public/apple-touch-icon-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/public/apple-touch-icon-precomposed.png
--------------------------------------------------------------------------------
/rails_5_test_app/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/rails_5_test_app/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/public/favicon.ico
--------------------------------------------------------------------------------
/rails_5_test_app/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 |
--------------------------------------------------------------------------------
/rails_5_test_app/spec/controllers/tests_controller_spec.rb:
--------------------------------------------------------------------------------
1 | require 'rails_helper'
2 |
3 | RSpec.describe TestsController, type: :controller do
4 | let(:json_body) { JSON.parse(response.body, symbolize_names: true) }
5 |
6 | it "re-raises the error when something goes wrong with the rendering process" do
7 | described_class.send(:handle_api_errors)
8 | allow_any_instance_of(TestsController)
9 | .to receive(:render)
10 | .and_raise("This is not the error that should be raised")
11 |
12 | expect { get :runtime_error }.to raise_error(RuntimeError, "This is a RuntimeError!")
13 | end
14 |
15 | context "with defaults" do
16 | before do
17 | described_class.send(:handle_api_errors)
18 | end
19 |
20 | it "renders the error in JSON format" do
21 | get :runtime_error
22 |
23 | expect(json_body).to eq(
24 | error: {
25 | title: "Internal Server Error",
26 | detail: "This is a RuntimeError!"
27 | }
28 | )
29 | end
30 |
31 | it "sets the status code based on the ActionDispatch::ExceptionWrapper.rescue_responses mapping" do
32 | get :runtime_error
33 | expect(response.code).to eq("500")
34 |
35 | get :record_not_found
36 | expect(response.code).to eq("404")
37 |
38 | get :not_implemented
39 | expect(response.code).to eq("501")
40 |
41 | get :custom_auth_error
42 | expect(response.code).to eq("401")
43 | end
44 |
45 | it "sets the content type to application/json" do
46 | get :runtime_error
47 | expect(response.content_type).to start_with("application/json")
48 | end
49 | end
50 |
51 | context "when the format is set to :json_api" do
52 | before do
53 | described_class.send(:handle_api_errors, format: :json_api)
54 | end
55 |
56 | it "sets the content_type to application/vnd.api+json" do
57 | get :runtime_error
58 |
59 | expect(response.content_type).to start_with("application/vnd.api+json")
60 | end
61 |
62 | it "can render errros in JSON:API format" do
63 | get :runtime_error
64 |
65 | expect(json_body).to eq(
66 | errors: [
67 | {
68 | title: "Internal Server Error",
69 | detail: "This is a RuntimeError!",
70 | status: "500"
71 | }
72 | ]
73 | )
74 | end
75 | end
76 |
77 | context "when using a custom serializer" do
78 | let(:custom_serializer) do
79 | Class.new(ApiErrorHandler::Serializers::BaseSerializer) do
80 | def serialize(serializer_options)
81 | "Error! Title: #{title} Status Code: #{status_code}"
82 | end
83 |
84 | def render_format
85 | :plain
86 | end
87 | end
88 | end
89 |
90 | before do
91 | described_class.send(:handle_api_errors, serializer: custom_serializer)
92 | end
93 |
94 | it "renders the body using the custom serializer's serialize method" do
95 | get :runtime_error
96 |
97 | expect(response.body).to eq("Error! Title: Internal Server Error Status Code: 500")
98 | expect(response.content_type).to start_with("text/plain")
99 | end
100 | end
101 |
102 | context "when you provide the error_reporter option" do
103 | it "reports errors" do
104 | error_reporter = double(report: true)
105 | described_class.send(
106 | :handle_api_errors,
107 | error_reporter: Proc.new { |error| error_reporter.report(error) }
108 | )
109 |
110 | expect(error_reporter).to receive(:report).with(instance_of(RuntimeError))
111 |
112 | get :runtime_error
113 | end
114 | end
115 |
116 | context "when you also provide both the error_reporter and error_id options" do
117 | it "reports the error with the error id" do
118 | error_reporter = double(report: true)
119 | described_class.send(
120 | :handle_api_errors,
121 | error_id: Proc.new { "error_id" },
122 | error_reporter: Proc.new { |error, error_id| error_reporter.report(error, error_id) }
123 | )
124 |
125 | expect(error_reporter)
126 | .to receive(:report)
127 | .with(instance_of(RuntimeError), "error_id")
128 |
129 | get :runtime_error
130 | end
131 | end
132 |
133 | context "when you include the backtrace option" do
134 | it "displays the error's backtrace" do
135 | described_class.send(:handle_api_errors, backtrace: true)
136 |
137 | get :runtime_error
138 |
139 | expect(json_body.dig(:error, :backtrace)).to be_present
140 | end
141 | end
142 | end
143 |
--------------------------------------------------------------------------------
/rails_5_test_app/spec/rails_helper.rb:
--------------------------------------------------------------------------------
1 | # This file is copied to spec/ when you run 'rails generate rspec:install'
2 | require 'spec_helper'
3 | ENV['RAILS_ENV'] ||= 'test'
4 | require File.expand_path('../../config/environment', __FILE__)
5 | # Prevent database truncation if the environment is production
6 | abort("The Rails environment is running in production mode!") if Rails.env.production?
7 | require 'rspec/rails'
8 | # Add additional requires below this line. Rails is not loaded until this point!
9 |
10 | # Requires supporting ruby files with custom matchers and macros, etc, in
11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
12 | # run as spec files by default. This means that files in spec/support that end
13 | # in _spec.rb will both be required and run as specs, causing the specs to be
14 | # run twice. It is recommended that you do not name files matching this glob to
15 | # end with _spec.rb. You can configure this pattern with the --pattern
16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
17 | #
18 | # The following line is provided for convenience purposes. It has the downside
19 | # of increasing the boot-up time by auto-requiring all files in the support
20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually
21 | # require only the support files necessary.
22 | #
23 | # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
24 |
25 | # Checks for pending migrations and applies them before tests are run.
26 | # If you are not using ActiveRecord, you can remove these lines.
27 | begin
28 | ActiveRecord::Migration.maintain_test_schema!
29 | rescue ActiveRecord::PendingMigrationError => e
30 | puts e.to_s.strip
31 | exit 1
32 | end
33 | RSpec.configure do |config|
34 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
35 | config.fixture_path = "#{::Rails.root}/spec/fixtures"
36 |
37 | # If you're not using ActiveRecord, or you'd prefer not to run each of your
38 | # examples within a transaction, remove the following line or assign false
39 | # instead of true.
40 | config.use_transactional_fixtures = true
41 |
42 | # RSpec Rails can automatically mix in different behaviours to your tests
43 | # based on their file location, for example enabling you to call `get` and
44 | # `post` in specs under `spec/controllers`.
45 | #
46 | # You can disable this behaviour by removing the line below, and instead
47 | # explicitly tag your specs with their type, e.g.:
48 | #
49 | # RSpec.describe UsersController, :type => :controller do
50 | # # ...
51 | # end
52 | #
53 | # The different available types are documented in the features, such as in
54 | # https://relishapp.com/rspec/rspec-rails/docs
55 | config.infer_spec_type_from_file_location!
56 |
57 | # Filter lines from Rails gems in backtraces.
58 | config.filter_rails_from_backtrace!
59 | # arbitrary gems may also be filtered via:
60 | # config.filter_gems_from_backtrace("gem name")
61 | end
62 |
--------------------------------------------------------------------------------
/rails_5_test_app/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3 | # The generated `.rspec` file contains `--require spec_helper` which will cause
4 | # this file to always be loaded, without a need to explicitly require it in any
5 | # files.
6 | #
7 | # Given that it is always loaded, you are encouraged to keep this file as
8 | # light-weight as possible. Requiring heavyweight dependencies from this file
9 | # will add to the boot time of your test suite on EVERY test run, even for an
10 | # individual file that may not need all of that loaded. Instead, consider making
11 | # a separate helper file that requires the additional dependencies and performs
12 | # the additional setup, and require it from the spec files that actually need
13 | # it.
14 | #
15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
16 | RSpec.configure do |config|
17 | # rspec-expectations config goes here. You can use an alternate
18 | # assertion/expectation library such as wrong or the stdlib/minitest
19 | # assertions if you prefer.
20 | config.expect_with :rspec do |expectations|
21 | # This option will default to `true` in RSpec 4. It makes the `description`
22 | # and `failure_message` of custom matchers include text for helper methods
23 | # defined using `chain`, e.g.:
24 | # be_bigger_than(2).and_smaller_than(4).description
25 | # # => "be bigger than 2 and smaller than 4"
26 | # ...rather than:
27 | # # => "be bigger than 2"
28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true
29 | end
30 |
31 | # rspec-mocks config goes here. You can use an alternate test double
32 | # library (such as bogus or mocha) by changing the `mock_with` option here.
33 | config.mock_with :rspec do |mocks|
34 | # Prevents you from mocking or stubbing a method that does not exist on
35 | # a real object. This is generally recommended, and will default to
36 | # `true` in RSpec 4.
37 | mocks.verify_partial_doubles = true
38 | end
39 |
40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
41 | # have no way to turn it off -- the option exists only for backwards
42 | # compatibility in RSpec 3). It causes shared context metadata to be
43 | # inherited by the metadata hash of host groups and examples, rather than
44 | # triggering implicit auto-inclusion in groups with matching metadata.
45 | config.shared_context_metadata_behavior = :apply_to_host_groups
46 |
47 | # The settings below are suggested to provide a good initial experience
48 | # with RSpec, but feel free to customize to your heart's content.
49 | =begin
50 | # This allows you to limit a spec run to individual examples or groups
51 | # you care about by tagging them with `:focus` metadata. When nothing
52 | # is tagged with `:focus`, all examples get run. RSpec also provides
53 | # aliases for `it`, `describe`, and `context` that include `:focus`
54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
55 | config.filter_run_when_matching :focus
56 |
57 | # Allows RSpec to persist some state between runs in order to support
58 | # the `--only-failures` and `--next-failure` CLI options. We recommend
59 | # you configure your source control system to ignore this file.
60 | config.example_status_persistence_file_path = "spec/examples.txt"
61 |
62 | # Limits the available syntax to the non-monkey patched syntax that is
63 | # recommended. For more details, see:
64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
67 | config.disable_monkey_patching!
68 |
69 | # Many RSpec users commonly either run the entire suite or an individual
70 | # file, and it's useful to allow more verbose output when running an
71 | # individual spec file.
72 | if config.files_to_run.one?
73 | # Use the documentation formatter for detailed output,
74 | # unless a formatter has already been configured
75 | # (e.g. via a command-line flag).
76 | config.default_formatter = "doc"
77 | end
78 |
79 | # Print the 10 slowest examples and example groups at the
80 | # end of the spec run, to help surface which specs are running
81 | # particularly slow.
82 | config.profile_examples = 10
83 |
84 | # Run specs in random order to surface order dependencies. If you find an
85 | # order dependency and want to debug it, you can fix the order by providing
86 | # the seed, which is printed after each run.
87 | # --seed 1234
88 | config.order = :random
89 |
90 | # Seed global randomization in this process using the `--seed` CLI option.
91 | # Setting this allows you to use `--seed` to deterministically reproduce
92 | # test failures related to randomization by passing the same `--seed` value
93 | # as the one that triggered the failure.
94 | Kernel.srand config.seed
95 | =end
96 | end
97 |
--------------------------------------------------------------------------------
/rails_5_test_app/storage/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/storage/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/application_system_test_case.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
4 | driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
5 | end
6 |
--------------------------------------------------------------------------------
/rails_5_test_app/test/controllers/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/controllers/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/fixtures/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/fixtures/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/fixtures/files/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/fixtures/files/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/helpers/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/helpers/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/integration/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/integration/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/mailers/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/mailers/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/models/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/models/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/system/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/test/system/.keep
--------------------------------------------------------------------------------
/rails_5_test_app/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | ENV['RAILS_ENV'] ||= 'test'
2 | require_relative '../config/environment'
3 | require 'rails/test_help'
4 |
5 | class ActiveSupport::TestCase
6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
7 | fixtures :all
8 |
9 | # Add more helper methods to be used by all tests here...
10 | end
11 |
--------------------------------------------------------------------------------
/rails_5_test_app/vendor/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_5_test_app/vendor/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/.rspec:
--------------------------------------------------------------------------------
1 | --require spec_helper
2 |
--------------------------------------------------------------------------------
/rails_6_test_app/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.5.1
2 |
--------------------------------------------------------------------------------
/rails_6_test_app/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" }
3 |
4 | ruby '>= 2.5.1'
5 |
6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
7 | gem 'rails', '~> 6.0.0'
8 | # Use sqlite3 as the database for Active Record
9 | gem 'sqlite3', '~> 1.4'
10 | # Use Puma as the app server
11 | gem 'puma', '~> 3.11'
12 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
13 | gem 'jbuilder', '~> 2.7'
14 | # Use Active Model has_secure_password
15 | # gem 'bcrypt', '~> 3.1.7'
16 |
17 | # Use Active Storage variant
18 | # gem 'image_processing', '~> 1.2'
19 |
20 | # Reduces boot times through caching; required in config/boot.rb
21 | gem 'bootsnap', '>= 1.4.2', require: false
22 |
23 | gem 'api_error_handler', path: '..'
24 |
25 | group :development, :test do
26 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console
27 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
28 | gem 'rspec-rails', '~> 3.8.2'
29 | end
30 |
31 | group :development do
32 | # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
33 | gem 'web-console', '>= 3.3.0'
34 | gem 'listen', '>= 3.0.5', '< 3.2'
35 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
36 | gem 'spring'
37 | gem 'spring-watcher-listen', '~> 2.0.0'
38 | end
39 |
40 | group :test do
41 | # Adds support for Capybara system testing and selenium driver
42 | # gem 'capybara', '>= 2.15'
43 | # gem 'selenium-webdriver'
44 | # Easy installation and use of web drivers to run system tests with browsers
45 | # gem 'webdrivers'
46 | end
47 |
48 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
49 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
50 |
--------------------------------------------------------------------------------
/rails_6_test_app/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: ..
3 | specs:
4 | api_error_handler (0.2.0)
5 | actionpack (>= 5.0)
6 | activesupport (>= 5.0)
7 | rack (>= 1.0)
8 |
9 | GEM
10 | remote: https://rubygems.org/
11 | specs:
12 | actioncable (6.0.3.6)
13 | actionpack (= 6.0.3.6)
14 | nio4r (~> 2.0)
15 | websocket-driver (>= 0.6.1)
16 | actionmailbox (6.0.3.6)
17 | actionpack (= 6.0.3.6)
18 | activejob (= 6.0.3.6)
19 | activerecord (= 6.0.3.6)
20 | activestorage (= 6.0.3.6)
21 | activesupport (= 6.0.3.6)
22 | mail (>= 2.7.1)
23 | actionmailer (6.0.3.6)
24 | actionpack (= 6.0.3.6)
25 | actionview (= 6.0.3.6)
26 | activejob (= 6.0.3.6)
27 | mail (~> 2.5, >= 2.5.4)
28 | rails-dom-testing (~> 2.0)
29 | actionpack (6.0.3.6)
30 | actionview (= 6.0.3.6)
31 | activesupport (= 6.0.3.6)
32 | rack (~> 2.0, >= 2.0.8)
33 | rack-test (>= 0.6.3)
34 | rails-dom-testing (~> 2.0)
35 | rails-html-sanitizer (~> 1.0, >= 1.2.0)
36 | actiontext (6.0.3.6)
37 | actionpack (= 6.0.3.6)
38 | activerecord (= 6.0.3.6)
39 | activestorage (= 6.0.3.6)
40 | activesupport (= 6.0.3.6)
41 | nokogiri (>= 1.8.5)
42 | actionview (6.0.3.6)
43 | activesupport (= 6.0.3.6)
44 | builder (~> 3.1)
45 | erubi (~> 1.4)
46 | rails-dom-testing (~> 2.0)
47 | rails-html-sanitizer (~> 1.1, >= 1.2.0)
48 | activejob (6.0.3.6)
49 | activesupport (= 6.0.3.6)
50 | globalid (>= 0.3.6)
51 | activemodel (6.0.3.6)
52 | activesupport (= 6.0.3.6)
53 | activerecord (6.0.3.6)
54 | activemodel (= 6.0.3.6)
55 | activesupport (= 6.0.3.6)
56 | activestorage (6.0.3.6)
57 | actionpack (= 6.0.3.6)
58 | activejob (= 6.0.3.6)
59 | activerecord (= 6.0.3.6)
60 | marcel (~> 1.0.0)
61 | activesupport (6.0.3.6)
62 | concurrent-ruby (~> 1.0, >= 1.0.2)
63 | i18n (>= 0.7, < 2)
64 | minitest (~> 5.1)
65 | tzinfo (~> 1.1)
66 | zeitwerk (~> 2.2, >= 2.2.2)
67 | bindex (0.8.1)
68 | bootsnap (1.7.3)
69 | msgpack (~> 1.0)
70 | builder (3.2.4)
71 | byebug (11.1.3)
72 | concurrent-ruby (1.1.8)
73 | crass (1.0.6)
74 | diff-lcs (1.4.4)
75 | erubi (1.10.0)
76 | ffi (1.15.0)
77 | globalid (0.4.2)
78 | activesupport (>= 4.2.0)
79 | i18n (1.8.10)
80 | concurrent-ruby (~> 1.0)
81 | jbuilder (2.11.2)
82 | activesupport (>= 5.0.0)
83 | listen (3.1.5)
84 | rb-fsevent (~> 0.9, >= 0.9.4)
85 | rb-inotify (~> 0.9, >= 0.9.7)
86 | ruby_dep (~> 1.2)
87 | loofah (2.9.0)
88 | crass (~> 1.0.2)
89 | nokogiri (>= 1.5.9)
90 | mail (2.7.1)
91 | mini_mime (>= 0.1.1)
92 | marcel (1.0.1)
93 | method_source (1.0.0)
94 | mini_mime (1.1.0)
95 | mini_portile2 (2.5.0)
96 | minitest (5.14.4)
97 | msgpack (1.4.2)
98 | nio4r (2.5.7)
99 | nokogiri (1.11.2)
100 | mini_portile2 (~> 2.5.0)
101 | racc (~> 1.4)
102 | puma (3.12.6)
103 | racc (1.5.2)
104 | rack (2.2.3)
105 | rack-test (1.1.0)
106 | rack (>= 1.0, < 3)
107 | rails (6.0.3.6)
108 | actioncable (= 6.0.3.6)
109 | actionmailbox (= 6.0.3.6)
110 | actionmailer (= 6.0.3.6)
111 | actionpack (= 6.0.3.6)
112 | actiontext (= 6.0.3.6)
113 | actionview (= 6.0.3.6)
114 | activejob (= 6.0.3.6)
115 | activemodel (= 6.0.3.6)
116 | activerecord (= 6.0.3.6)
117 | activestorage (= 6.0.3.6)
118 | activesupport (= 6.0.3.6)
119 | bundler (>= 1.3.0)
120 | railties (= 6.0.3.6)
121 | sprockets-rails (>= 2.0.0)
122 | rails-dom-testing (2.0.3)
123 | activesupport (>= 4.2.0)
124 | nokogiri (>= 1.6)
125 | rails-html-sanitizer (1.3.0)
126 | loofah (~> 2.3)
127 | railties (6.0.3.6)
128 | actionpack (= 6.0.3.6)
129 | activesupport (= 6.0.3.6)
130 | method_source
131 | rake (>= 0.8.7)
132 | thor (>= 0.20.3, < 2.0)
133 | rake (13.0.3)
134 | rb-fsevent (0.10.4)
135 | rb-inotify (0.10.1)
136 | ffi (~> 1.0)
137 | rspec-core (3.8.2)
138 | rspec-support (~> 3.8.0)
139 | rspec-expectations (3.8.6)
140 | diff-lcs (>= 1.2.0, < 2.0)
141 | rspec-support (~> 3.8.0)
142 | rspec-mocks (3.8.2)
143 | diff-lcs (>= 1.2.0, < 2.0)
144 | rspec-support (~> 3.8.0)
145 | rspec-rails (3.8.3)
146 | actionpack (>= 3.0)
147 | activesupport (>= 3.0)
148 | railties (>= 3.0)
149 | rspec-core (~> 3.8.0)
150 | rspec-expectations (~> 3.8.0)
151 | rspec-mocks (~> 3.8.0)
152 | rspec-support (~> 3.8.0)
153 | rspec-support (3.8.3)
154 | ruby_dep (1.5.0)
155 | spring (2.1.1)
156 | spring-watcher-listen (2.0.1)
157 | listen (>= 2.7, < 4.0)
158 | spring (>= 1.2, < 3.0)
159 | sprockets (4.0.2)
160 | concurrent-ruby (~> 1.0)
161 | rack (> 1, < 3)
162 | sprockets-rails (3.2.2)
163 | actionpack (>= 4.0)
164 | activesupport (>= 4.0)
165 | sprockets (>= 3.0.0)
166 | sqlite3 (1.4.2)
167 | thor (1.1.0)
168 | thread_safe (0.3.6)
169 | tzinfo (1.2.9)
170 | thread_safe (~> 0.1)
171 | web-console (4.1.0)
172 | actionview (>= 6.0.0)
173 | activemodel (>= 6.0.0)
174 | bindex (>= 0.4.0)
175 | railties (>= 6.0.0)
176 | websocket-driver (0.7.3)
177 | websocket-extensions (>= 0.1.0)
178 | websocket-extensions (0.1.5)
179 | zeitwerk (2.4.2)
180 |
181 | PLATFORMS
182 | ruby
183 |
184 | DEPENDENCIES
185 | api_error_handler!
186 | bootsnap (>= 1.4.2)
187 | byebug
188 | jbuilder (~> 2.7)
189 | listen (>= 3.0.5, < 3.2)
190 | puma (~> 3.11)
191 | rails (~> 6.0.0)
192 | rspec-rails (~> 3.8.2)
193 | spring
194 | spring-watcher-listen (~> 2.0.0)
195 | sqlite3 (~> 1.4)
196 | tzinfo-data
197 | web-console (>= 3.3.0)
198 |
199 | RUBY VERSION
200 | ruby 2.7.2p137
201 |
202 | BUNDLED WITH
203 | 2.2.15
204 |
--------------------------------------------------------------------------------
/rails_6_test_app/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require_relative 'config/application'
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/assets/config/manifest.js:
--------------------------------------------------------------------------------
1 | //= link_tree ../images
2 | //= link_directory ../stylesheets .css
3 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/assets/images/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/app/assets/images/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
6 | * vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10 | * files in this directory. Styles in this file should be added after the last require_* statement.
11 | * It is generally better to create a new file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | end
3 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/app/controllers/concerns/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/app/controllers/tests_controller.rb:
--------------------------------------------------------------------------------
1 | class TestsController < ApplicationController
2 | handle_api_errors()
3 |
4 | def runtime_error
5 | raise RuntimeError, "This is a RuntimeError!"
6 | end
7 |
8 | def record_not_found
9 | raise ActiveRecord::RecordNotFound, "Not found!"
10 | end
11 |
12 | def not_implemented
13 | raise ActionController::NotImplemented, "Not Implemented!"
14 | end
15 |
16 | def custom_auth_error
17 | # `config.action_dispatch.rescue_responses` has been altered to map this
18 | # error to the :unauthorized status code in config/application.rb
19 | raise CustomAuthError, "Custom authentication error!"
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/errors/custom_auth_error.rb:
--------------------------------------------------------------------------------
1 | class CustomAuthError < StandardError; end
2 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/jobs/application_job.rb:
--------------------------------------------------------------------------------
1 | class ApplicationJob < ActiveJob::Base
2 | # Automatically retry jobs that encountered a deadlock
3 | # retry_on ActiveRecord::Deadlocked
4 |
5 | # Most jobs are safe to ignore if the underlying records are no longer available
6 | # discard_on ActiveJob::DeserializationError
7 | end
8 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/models/application_record.rb:
--------------------------------------------------------------------------------
1 | class ApplicationRecord < ActiveRecord::Base
2 | self.abstract_class = true
3 | end
4 |
--------------------------------------------------------------------------------
/rails_6_test_app/app/models/concerns/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/app/models/concerns/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Rails6TestApp
5 | <%= csrf_meta_tags %>
6 | <%= csp_meta_tag %>
7 |
8 | <%= stylesheet_link_tag 'application', media: 'all' %>
9 |
10 |
11 |
12 | <%= yield %>
13 |
14 |
15 |
--------------------------------------------------------------------------------
/rails_6_test_app/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | # frozen_string_literal: true
3 |
4 | #
5 | # This file was generated by Bundler.
6 | #
7 | # The application 'bundle' is installed as part of a gem, and
8 | # this file is here to facilitate running it.
9 | #
10 |
11 | require "rubygems"
12 |
13 | m = Module.new do
14 | module_function
15 |
16 | def invoked_as_script?
17 | File.expand_path($0) == File.expand_path(__FILE__)
18 | end
19 |
20 | def env_var_version
21 | ENV["BUNDLER_VERSION"]
22 | end
23 |
24 | def cli_arg_version
25 | return unless invoked_as_script? # don't want to hijack other binstubs
26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
27 | bundler_version = nil
28 | update_index = nil
29 | ARGV.each_with_index do |a, i|
30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
31 | bundler_version = a
32 | end
33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
34 | bundler_version = $1 || ">= 0.a"
35 | update_index = i
36 | end
37 | bundler_version
38 | end
39 |
40 | def gemfile
41 | gemfile = ENV["BUNDLE_GEMFILE"]
42 | return gemfile if gemfile && !gemfile.empty?
43 |
44 | File.expand_path("../../Gemfile", __FILE__)
45 | end
46 |
47 | def lockfile
48 | lockfile =
49 | case File.basename(gemfile)
50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
51 | else "#{gemfile}.lock"
52 | end
53 | File.expand_path(lockfile)
54 | end
55 |
56 | def lockfile_version
57 | return unless File.file?(lockfile)
58 | lockfile_contents = File.read(lockfile)
59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
60 | Regexp.last_match(1)
61 | end
62 |
63 | def bundler_version
64 | @bundler_version ||= begin
65 | env_var_version || cli_arg_version ||
66 | lockfile_version || "#{Gem::Requirement.default}.a"
67 | end
68 | end
69 |
70 | def load_bundler!
71 | ENV["BUNDLE_GEMFILE"] ||= gemfile
72 |
73 | # must dup string for RG < 1.8 compatibility
74 | activate_bundler(bundler_version.dup)
75 | end
76 |
77 | def activate_bundler(bundler_version)
78 | if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
79 | bundler_version = "< 2"
80 | end
81 | gem_error = activation_error_handling do
82 | gem "bundler", bundler_version
83 | end
84 | return if gem_error.nil?
85 | require_error = activation_error_handling do
86 | require "bundler/version"
87 | end
88 | return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
89 | warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
90 | exit 42
91 | end
92 |
93 | def activation_error_handling
94 | yield
95 | nil
96 | rescue StandardError, LoadError => e
97 | e
98 | end
99 | end
100 |
101 | m.load_bundler!
102 |
103 | if m.invoked_as_script?
104 | load Gem.bin_path("bundler", "bundle")
105 | end
106 |
--------------------------------------------------------------------------------
/rails_6_test_app/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | APP_PATH = File.expand_path('../config/application', __dir__)
8 | require_relative '../config/boot'
9 | require 'rails/commands'
10 |
--------------------------------------------------------------------------------
/rails_6_test_app/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | begin
3 | load File.expand_path('../spring', __FILE__)
4 | rescue LoadError => e
5 | raise unless e.message.include?('spring')
6 | end
7 | require_relative '../config/boot'
8 | require 'rake'
9 | Rake.application.run
10 |
--------------------------------------------------------------------------------
/rails_6_test_app/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require 'fileutils'
3 |
4 | # path to your application root.
5 | APP_ROOT = File.expand_path('..', __dir__)
6 |
7 | def system!(*args)
8 | system(*args) || abort("\n== Command #{args} failed ==")
9 | end
10 |
11 | FileUtils.chdir APP_ROOT do
12 | # This script is a way to setup or update your development environment automatically.
13 | # This script is idempotent, so that you can run it at anytime and get an expectable outcome.
14 | # Add necessary setup steps to this file.
15 |
16 | puts '== Installing dependencies =='
17 | system! 'gem install bundler --conservative'
18 | system('bundle check') || system!('bundle install')
19 |
20 | # puts "\n== Copying sample files =="
21 | # unless File.exist?('config/database.yml')
22 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml'
23 | # end
24 |
25 | puts "\n== Preparing database =="
26 | system! 'bin/rails db:prepare'
27 |
28 | puts "\n== Removing old logs and tempfiles =="
29 | system! 'bin/rails log:clear tmp:clear'
30 |
31 | puts "\n== Restarting application server =="
32 | system! 'bin/rails restart'
33 | end
34 |
--------------------------------------------------------------------------------
/rails_6_test_app/bin/spring:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 |
3 | # This file loads Spring without using Bundler, in order to be fast.
4 | # It gets overwritten when you run the `spring binstub` command.
5 |
6 | unless defined?(Spring)
7 | require 'rubygems'
8 | require 'bundler'
9 |
10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
11 | spring = lockfile.specs.detect { |spec| spec.name == 'spring' }
12 | if spring
13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
14 | gem 'spring', spring.version
15 | require 'spring/binstub'
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/rails_6_test_app/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require_relative 'config/environment'
4 |
5 | run Rails.application
6 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative 'boot'
2 |
3 | require "rails"
4 | # Pick the frameworks you want:
5 | require "active_model/railtie"
6 | require "active_job/railtie"
7 | require "active_record/railtie"
8 | require "active_storage/engine"
9 | require "action_controller/railtie"
10 | # require "action_mailer/railtie"
11 | require "action_mailbox/engine"
12 | require "action_text/engine"
13 | require "action_view/railtie"
14 | # require "action_cable/engine"
15 | # require "sprockets/railtie"
16 | require "rails/test_unit/railtie"
17 |
18 | # Require the gems listed in Gemfile, including any gems
19 | # you've limited to :test, :development, or :production.
20 | Bundler.require(*Rails.groups)
21 |
22 | module Rails6TestApp
23 | class Application < Rails::Application
24 | # Initialize configuration defaults for originally generated Rails version.
25 | config.load_defaults 6.0
26 |
27 | # Settings in config/environments/* take precedence over those specified here.
28 | # Application configuration can go into files in config/initializers
29 | # -- all .rb files in that directory are automatically loaded after loading
30 | # the framework and any gems in your application.
31 |
32 | config.action_dispatch.rescue_responses.merge!(
33 | "CustomAuthError" => :unauthorized
34 | )
35 | end
36 | end
37 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/boot.rb:
--------------------------------------------------------------------------------
1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
2 |
3 | require 'bundler/setup' # Set up gems listed in the Gemfile.
4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
5 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/credentials.yml.enc:
--------------------------------------------------------------------------------
1 | govqP6vQcaWgw58svRu40wtFoRCee/3CVkTlQXQ4tj7hGFlTJyd12bT2NFvJfGH0+gCvqdpjDSdvkfSDkr4+1pVIK2IlNfcRQOdzDxjH5i+S+yFogctv3ScbIzJpd9EFl0SWj5cgIwLSLnHWIH3PfGEwM5AQxj53xTCaJjezBtYDkneGytrbhDDs3hoAR0pdk4D+WqyOBHjjNxxeEcmIvXGKqx7YYdKWGnShtSf/93ytiBggrJRSV+9EOBrVCq1sLdEAXDIg9qzwF8gu3CRL9vHTrkVQs9AdcHa8l0mPlrHiXd3D5vYqFp8dgFHa7FOW/nLqUwMsV48kZx4odPSUU6//fDZ0piXX+2PaxSQG5aRLwBGc1zG/8jUMreuF3Z/W2hWcjU5bUOVI6zGhhPKjZva/VlOKjTad4Mml--bomv0GIOlsZbfUu+--9kJXXw/2lBLyICXP4TaDow==
--------------------------------------------------------------------------------
/rails_6_test_app/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite. Versions 3.8.0 and up are supported.
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: sqlite3
9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: db/development.sqlite3
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: db/test.sqlite3
22 |
23 | production:
24 | <<: *default
25 | database: db/production.sqlite3
26 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative 'application'
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # In the development environment your application's code is reloaded on
5 | # every request. This slows down response time but is perfect for development
6 | # since you don't have to restart the web server when you make code changes.
7 | config.cache_classes = false
8 |
9 | # Do not eager load code on boot.
10 | config.eager_load = false
11 |
12 | # Show full error reports.
13 | config.consider_all_requests_local = true
14 |
15 | # Enable/disable caching. By default caching is disabled.
16 | # Run rails dev:cache to toggle caching.
17 | if Rails.root.join('tmp', 'caching-dev.txt').exist?
18 | config.action_controller.perform_caching = true
19 | config.action_controller.enable_fragment_cache_logging = true
20 |
21 | config.cache_store = :memory_store
22 | config.public_file_server.headers = {
23 | 'Cache-Control' => "public, max-age=#{2.days.to_i}"
24 | }
25 | else
26 | config.action_controller.perform_caching = false
27 |
28 | config.cache_store = :null_store
29 | end
30 |
31 | # Store uploaded files on the local file system (see config/storage.yml for options).
32 | config.active_storage.service = :local
33 |
34 | # Print deprecation notices to the Rails logger.
35 | config.active_support.deprecation = :log
36 |
37 | # Raise an error on page load if there are pending migrations.
38 | config.active_record.migration_error = :page_load
39 |
40 | # Highlight code that triggered database queries in logs.
41 | config.active_record.verbose_query_logs = true
42 |
43 |
44 | # Raises error for missing translations.
45 | # config.action_view.raise_on_missing_translations = true
46 |
47 | # Use an evented file watcher to asynchronously detect changes in source code,
48 | # routes, locales, etc. This feature depends on the listen gem.
49 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker
50 | end
51 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # Code is not reloaded between requests.
5 | config.cache_classes = true
6 |
7 | # Eager load code on boot. This eager loads most of Rails and
8 | # your application in memory, allowing both threaded web servers
9 | # and those relying on copy on write to perform better.
10 | # Rake tasks automatically ignore this option for performance.
11 | config.eager_load = true
12 |
13 | # Full error reports are disabled and caching is turned on.
14 | config.consider_all_requests_local = false
15 | config.action_controller.perform_caching = true
16 |
17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
19 | # config.require_master_key = true
20 |
21 | # Disable serving static files from the `/public` folder by default since
22 | # Apache or NGINX already handles this.
23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
24 |
25 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
26 | # config.action_controller.asset_host = 'http://assets.example.com'
27 |
28 | # Specifies the header that your server uses for sending files.
29 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
30 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
31 |
32 | # Store uploaded files on the local file system (see config/storage.yml for options).
33 | config.active_storage.service = :local
34 |
35 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
36 | # config.force_ssl = true
37 |
38 | # Use the lowest log level to ensure availability of diagnostic information
39 | # when problems arise.
40 | config.log_level = :debug
41 |
42 | # Prepend all log lines with the following tags.
43 | config.log_tags = [ :request_id ]
44 |
45 | # Use a different cache store in production.
46 | # config.cache_store = :mem_cache_store
47 |
48 | # Use a real queuing backend for Active Job (and separate queues per environment).
49 | # config.active_job.queue_adapter = :resque
50 | # config.active_job.queue_name_prefix = "rails_6_test_app_production"
51 |
52 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
53 | # the I18n.default_locale when a translation cannot be found).
54 | config.i18n.fallbacks = true
55 |
56 | # Send deprecation notices to registered listeners.
57 | config.active_support.deprecation = :notify
58 |
59 | # Use default logging formatter so that PID and timestamp are not suppressed.
60 | config.log_formatter = ::Logger::Formatter.new
61 |
62 | # Use a different logger for distributed setups.
63 | # require 'syslog/logger'
64 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
65 |
66 | if ENV["RAILS_LOG_TO_STDOUT"].present?
67 | logger = ActiveSupport::Logger.new(STDOUT)
68 | logger.formatter = config.log_formatter
69 | config.logger = ActiveSupport::TaggedLogging.new(logger)
70 | end
71 |
72 | # Do not dump schema after migrations.
73 | config.active_record.dump_schema_after_migration = false
74 |
75 | # Inserts middleware to perform automatic connection switching.
76 | # The `database_selector` hash is used to pass options to the DatabaseSelector
77 | # middleware. The `delay` is used to determine how long to wait after a write
78 | # to send a subsequent read to the primary.
79 | #
80 | # The `database_resolver` class is used by the middleware to determine which
81 | # database is appropriate to use based on the time delay.
82 | #
83 | # The `database_resolver_context` class is used by the middleware to set
84 | # timestamps for the last write to the primary. The resolver uses the context
85 | # class timestamps to determine how long to wait before reading from the
86 | # replica.
87 | #
88 | # By default Rails will store a last write timestamp in the session. The
89 | # DatabaseSelector middleware is designed as such you can define your own
90 | # strategy for connection switching and pass that into the middleware through
91 | # these configuration options.
92 | # config.active_record.database_selector = { delay: 2.seconds }
93 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
94 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
95 | end
96 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | # The test environment is used exclusively to run your application's
2 | # test suite. You never need to work with it otherwise. Remember that
3 | # your test database is "scratch space" for the test suite and is wiped
4 | # and recreated between test runs. Don't rely on the data there!
5 |
6 | Rails.application.configure do
7 | # Settings specified here will take precedence over those in config/application.rb.
8 |
9 | config.cache_classes = false
10 |
11 | # Do not eager load code on boot. This avoids loading your whole application
12 | # just for the purpose of running a single test. If you are using a tool that
13 | # preloads Rails for running tests, you may have to set it to true.
14 | config.eager_load = false
15 |
16 | # Configure public file server for tests with Cache-Control for performance.
17 | config.public_file_server.enabled = true
18 | config.public_file_server.headers = {
19 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}"
20 | }
21 |
22 | # Show full error reports and disable caching.
23 | config.consider_all_requests_local = true
24 | config.action_controller.perform_caching = false
25 | config.cache_store = :null_store
26 |
27 | # Raise exceptions instead of rendering exception templates.
28 | config.action_dispatch.show_exceptions = false
29 |
30 | # Disable request forgery protection in test environment.
31 | config.action_controller.allow_forgery_protection = false
32 |
33 | # Store uploaded files on the local file system in a temporary directory.
34 | config.active_storage.service = :test
35 |
36 | # Print deprecation notices to the stderr.
37 | config.active_support.deprecation = :stderr
38 |
39 | # Raises error for missing translations.
40 | # config.action_view.raise_on_missing_translations = true
41 | end
42 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ActiveSupport::Reloader.to_prepare do
4 | # ApplicationController.renderer.defaults.merge!(
5 | # http_host: 'example.org',
6 | # https: false
7 | # )
8 | # end
9 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/content_security_policy.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Define an application-wide content security policy
4 | # For further information see the following documentation
5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
6 |
7 | # Rails.application.config.content_security_policy do |policy|
8 | # policy.default_src :self, :https
9 | # policy.font_src :self, :https, :data
10 | # policy.img_src :self, :https, :data
11 | # policy.object_src :none
12 | # policy.script_src :self, :https
13 | # policy.style_src :self, :https
14 |
15 | # # Specify URI for violation reports
16 | # # policy.report_uri "/csp-violation-report-endpoint"
17 | # end
18 |
19 | # If you are using UJS then enable automatic nonce generation
20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
21 |
22 | # Set the nonce only to specific directives
23 | # Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
24 |
25 | # Report CSP violations to a specified URI
26 | # For further information see the following documentation:
27 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
28 | # Rails.application.config.content_security_policy_report_only = true
29 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # The following keys must be escaped otherwise they will not be retrieved by
20 | # the default I18n backend:
21 | #
22 | # true, false, on, off, yes, no
23 | #
24 | # Instead, surround them with single quotes.
25 | #
26 | # en:
27 | # 'true': 'foo'
28 | #
29 | # To learn more, please read the Rails Internationalization guide
30 | # available at https://guides.rubyonrails.org/i18n.html.
31 |
32 | en:
33 | hello: "Hello world"
34 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/master.key:
--------------------------------------------------------------------------------
1 | 6ba02514a0c391ae9f40b9afe1427383
--------------------------------------------------------------------------------
/rails_6_test_app/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers: a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum; this matches the default thread size of Active Record.
6 | #
7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
9 | threads min_threads_count, max_threads_count
10 |
11 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000.
12 | #
13 | port ENV.fetch("PORT") { 3000 }
14 |
15 | # Specifies the `environment` that Puma will run in.
16 | #
17 | environment ENV.fetch("RAILS_ENV") { "development" }
18 |
19 | # Specifies the `pidfile` that Puma will use.
20 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
21 |
22 | # Specifies the number of `workers` to boot in clustered mode.
23 | # Workers are forked web server processes. If using threads and workers together
24 | # the concurrency of the application would be max `threads` * `workers`.
25 | # Workers do not work on JRuby or Windows (both of which do not support
26 | # processes).
27 | #
28 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
29 |
30 | # Use the `preload_app!` method when specifying a `workers` number.
31 | # This directive tells Puma to first boot the application and load code
32 | # before forking the application. This takes advantage of Copy On Write
33 | # process behavior so workers use less memory.
34 | #
35 | # preload_app!
36 |
37 | # Allow puma to be restarted by `rails restart` command.
38 | plugin :tmp_restart
39 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
3 |
4 | get "/tests/runtime_error", controller: "tests"
5 | get "/tests/record_not_found", controller: "tests"
6 | get "/tests/not_implemented", controller: "tests"
7 | get "/tests/custom_auth_error", controller: "tests"
8 | end
9 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/spring.rb:
--------------------------------------------------------------------------------
1 | Spring.watch(
2 | ".ruby-version",
3 | ".rbenv-vars",
4 | "tmp/restart.txt",
5 | "tmp/caching-dev.txt"
6 | )
7 |
--------------------------------------------------------------------------------
/rails_6_test_app/config/storage.yml:
--------------------------------------------------------------------------------
1 | test:
2 | service: Disk
3 | root: <%= Rails.root.join("tmp/storage") %>
4 |
5 | local:
6 | service: Disk
7 | root: <%= Rails.root.join("storage") %>
8 |
9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
10 | # amazon:
11 | # service: S3
12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
14 | # region: us-east-1
15 | # bucket: your_own_bucket
16 |
17 | # Remember not to checkin your GCS keyfile to a repository
18 | # google:
19 | # service: GCS
20 | # project: your_project
21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
22 | # bucket: your_own_bucket
23 |
24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
25 | # microsoft:
26 | # service: AzureStorage
27 | # storage_account_name: your_account_name
28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
29 | # container: your_container_name
30 |
31 | # mirror:
32 | # service: Mirror
33 | # primary: local
34 | # mirrors: [ amazon, google, microsoft ]
35 |
--------------------------------------------------------------------------------
/rails_6_test_app/db/development.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/db/development.sqlite3
--------------------------------------------------------------------------------
/rails_6_test_app/db/seeds.rb:
--------------------------------------------------------------------------------
1 | # This file should contain all the record creation needed to seed the database with its default values.
2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
3 | #
4 | # Examples:
5 | #
6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
7 | # Character.create(name: 'Luke', movie: movies.first)
8 |
--------------------------------------------------------------------------------
/rails_6_test_app/db/test.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/db/test.sqlite3
--------------------------------------------------------------------------------
/rails_6_test_app/lib/assets/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/lib/assets/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/lib/tasks/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/lib/tasks/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/rails_6_test_app/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/rails_6_test_app/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/rails_6_test_app/public/apple-touch-icon-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/public/apple-touch-icon-precomposed.png
--------------------------------------------------------------------------------
/rails_6_test_app/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/rails_6_test_app/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/public/favicon.ico
--------------------------------------------------------------------------------
/rails_6_test_app/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 |
--------------------------------------------------------------------------------
/rails_6_test_app/spec/controllers/tests_controller_spec.rb:
--------------------------------------------------------------------------------
1 | ../../../rails_5_test_app/spec/controllers/tests_controller_spec.rb
--------------------------------------------------------------------------------
/rails_6_test_app/spec/rails_helper.rb:
--------------------------------------------------------------------------------
1 | # This file is copied to spec/ when you run 'rails generate rspec:install'
2 | require 'spec_helper'
3 | ENV['RAILS_ENV'] ||= 'test'
4 | require File.expand_path('../../config/environment', __FILE__)
5 | # Prevent database truncation if the environment is production
6 | abort("The Rails environment is running in production mode!") if Rails.env.production?
7 | require 'rspec/rails'
8 | # Add additional requires below this line. Rails is not loaded until this point!
9 |
10 | # Requires supporting ruby files with custom matchers and macros, etc, in
11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
12 | # run as spec files by default. This means that files in spec/support that end
13 | # in _spec.rb will both be required and run as specs, causing the specs to be
14 | # run twice. It is recommended that you do not name files matching this glob to
15 | # end with _spec.rb. You can configure this pattern with the --pattern
16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
17 | #
18 | # The following line is provided for convenience purposes. It has the downside
19 | # of increasing the boot-up time by auto-requiring all files in the support
20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually
21 | # require only the support files necessary.
22 | #
23 | # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
24 |
25 | # Checks for pending migrations and applies them before tests are run.
26 | # If you are not using ActiveRecord, you can remove these lines.
27 | begin
28 | ActiveRecord::Migration.maintain_test_schema!
29 | rescue ActiveRecord::PendingMigrationError => e
30 | puts e.to_s.strip
31 | exit 1
32 | end
33 | RSpec.configure do |config|
34 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
35 | config.fixture_path = "#{::Rails.root}/spec/fixtures"
36 |
37 | # If you're not using ActiveRecord, or you'd prefer not to run each of your
38 | # examples within a transaction, remove the following line or assign false
39 | # instead of true.
40 | config.use_transactional_fixtures = true
41 |
42 | # RSpec Rails can automatically mix in different behaviours to your tests
43 | # based on their file location, for example enabling you to call `get` and
44 | # `post` in specs under `spec/controllers`.
45 | #
46 | # You can disable this behaviour by removing the line below, and instead
47 | # explicitly tag your specs with their type, e.g.:
48 | #
49 | # RSpec.describe UsersController, :type => :controller do
50 | # # ...
51 | # end
52 | #
53 | # The different available types are documented in the features, such as in
54 | # https://relishapp.com/rspec/rspec-rails/docs
55 | config.infer_spec_type_from_file_location!
56 |
57 | # Filter lines from Rails gems in backtraces.
58 | config.filter_rails_from_backtrace!
59 | # arbitrary gems may also be filtered via:
60 | # config.filter_gems_from_backtrace("gem name")
61 | end
62 |
--------------------------------------------------------------------------------
/rails_6_test_app/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3 | # The generated `.rspec` file contains `--require spec_helper` which will cause
4 | # this file to always be loaded, without a need to explicitly require it in any
5 | # files.
6 | #
7 | # Given that it is always loaded, you are encouraged to keep this file as
8 | # light-weight as possible. Requiring heavyweight dependencies from this file
9 | # will add to the boot time of your test suite on EVERY test run, even for an
10 | # individual file that may not need all of that loaded. Instead, consider making
11 | # a separate helper file that requires the additional dependencies and performs
12 | # the additional setup, and require it from the spec files that actually need
13 | # it.
14 | #
15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
16 | RSpec.configure do |config|
17 | # rspec-expectations config goes here. You can use an alternate
18 | # assertion/expectation library such as wrong or the stdlib/minitest
19 | # assertions if you prefer.
20 | config.expect_with :rspec do |expectations|
21 | # This option will default to `true` in RSpec 4. It makes the `description`
22 | # and `failure_message` of custom matchers include text for helper methods
23 | # defined using `chain`, e.g.:
24 | # be_bigger_than(2).and_smaller_than(4).description
25 | # # => "be bigger than 2 and smaller than 4"
26 | # ...rather than:
27 | # # => "be bigger than 2"
28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true
29 | end
30 |
31 | # rspec-mocks config goes here. You can use an alternate test double
32 | # library (such as bogus or mocha) by changing the `mock_with` option here.
33 | config.mock_with :rspec do |mocks|
34 | # Prevents you from mocking or stubbing a method that does not exist on
35 | # a real object. This is generally recommended, and will default to
36 | # `true` in RSpec 4.
37 | mocks.verify_partial_doubles = true
38 | end
39 |
40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
41 | # have no way to turn it off -- the option exists only for backwards
42 | # compatibility in RSpec 3). It causes shared context metadata to be
43 | # inherited by the metadata hash of host groups and examples, rather than
44 | # triggering implicit auto-inclusion in groups with matching metadata.
45 | config.shared_context_metadata_behavior = :apply_to_host_groups
46 |
47 | # The settings below are suggested to provide a good initial experience
48 | # with RSpec, but feel free to customize to your heart's content.
49 | =begin
50 | # This allows you to limit a spec run to individual examples or groups
51 | # you care about by tagging them with `:focus` metadata. When nothing
52 | # is tagged with `:focus`, all examples get run. RSpec also provides
53 | # aliases for `it`, `describe`, and `context` that include `:focus`
54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
55 | config.filter_run_when_matching :focus
56 |
57 | # Allows RSpec to persist some state between runs in order to support
58 | # the `--only-failures` and `--next-failure` CLI options. We recommend
59 | # you configure your source control system to ignore this file.
60 | config.example_status_persistence_file_path = "spec/examples.txt"
61 |
62 | # Limits the available syntax to the non-monkey patched syntax that is
63 | # recommended. For more details, see:
64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
67 | config.disable_monkey_patching!
68 |
69 | # Many RSpec users commonly either run the entire suite or an individual
70 | # file, and it's useful to allow more verbose output when running an
71 | # individual spec file.
72 | if config.files_to_run.one?
73 | # Use the documentation formatter for detailed output,
74 | # unless a formatter has already been configured
75 | # (e.g. via a command-line flag).
76 | config.default_formatter = "doc"
77 | end
78 |
79 | # Print the 10 slowest examples and example groups at the
80 | # end of the spec run, to help surface which specs are running
81 | # particularly slow.
82 | config.profile_examples = 10
83 |
84 | # Run specs in random order to surface order dependencies. If you find an
85 | # order dependency and want to debug it, you can fix the order by providing
86 | # the seed, which is printed after each run.
87 | # --seed 1234
88 | config.order = :random
89 |
90 | # Seed global randomization in this process using the `--seed` CLI option.
91 | # Setting this allows you to use `--seed` to deterministically reproduce
92 | # test failures related to randomization by passing the same `--seed` value
93 | # as the one that triggered the failure.
94 | Kernel.srand config.seed
95 | =end
96 | end
97 |
--------------------------------------------------------------------------------
/rails_6_test_app/storage/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/storage/.keep
--------------------------------------------------------------------------------
/rails_6_test_app/vendor/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jamesstonehill/api_error_handler/c1635fd71e370e297e00d90fd8a7a07c6ab2d229/rails_6_test_app/vendor/.keep
--------------------------------------------------------------------------------
/spec/api_error_handler/error_id_generator_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "../../lib/api_error_handler/error_id_generator"
4 |
5 | RSpec.describe ApiErrorHandler::ErrorIdGenerator do
6 | it "Returns the result of the proc if you git it a proc" do
7 | expect(described_class.run(proc { "Result!" })).to eq("Result!")
8 | end
9 |
10 | it "Returns the result of the lambda if you git it a lambda" do
11 | expect(described_class.run(-> { "Result!" })).to eq("Result!")
12 | end
13 |
14 | it "Returns a UUID if you give it :uuid" do
15 | allow(SecureRandom).to receive(:uuid).and_return("Result!")
16 |
17 | expect(described_class.run(:uuid)).to eq("Result!")
18 | end
19 |
20 | it "Raises an error if you give it something it doesn't recognise" do
21 | expect do
22 | described_class.run(:foo)
23 | end.to raise_error(ApiErrorHandler::InvalidOptionError)
24 | end
25 | end
26 |
--------------------------------------------------------------------------------
/spec/api_error_handler/error_reporter_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "../../lib/api_error_handler/error_reporter"
4 |
5 | RSpec.describe ApiErrorHandler::ErrorReporter do
6 | let(:error) { RuntimeError.new("Error message") }
7 |
8 | it "Raises an InvalidOptionError if you provide an bad option" do
9 | reporter = described_class.new(:asdf)
10 |
11 | expect do
12 | reporter.report(error)
13 | end.to raise_error(ApiErrorHandler::InvalidOptionError)
14 | end
15 |
16 | context "using the `nil` strategy" do
17 | let(:reporter) { described_class.new(nil) }
18 |
19 | it "Does nothing if the strategy is `nil`" do
20 | reporter.report(error)
21 | end
22 | end
23 |
24 | context "using a Proc strategy" do
25 | it "Calls the Proc with the error and error_id" do
26 | strategy = proc do |e, error_id|
27 | expect(e).to eq(error)
28 | expect(error_id).to eq("123")
29 | end
30 |
31 | reporter = described_class.new(strategy)
32 |
33 | reporter.report(error, error_id: "123")
34 | end
35 | end
36 |
37 | context "using the :honeybadger strategy" do
38 | let(:reporter) { described_class.new(:honeybadger) }
39 |
40 | it "Raises an error if the Honeybadger constant is not defined" do
41 | expect { reporter.report(error) }.to raise_error(ApiErrorHandler::MissingDependencyError)
42 | end
43 |
44 | it "Reports to Honeybadger with an error id" do
45 | stub_const("Honeybadger", double)
46 | expect(Honeybadger).to receive(:notify).with(error, context: { error_id: "456" })
47 |
48 | reporter.report(error, error_id: "456")
49 | end
50 |
51 | it "Reports to Honeybadger without an error id" do
52 | stub_const("Honeybadger", double)
53 | expect(Honeybadger).to receive(:notify).with(error, context: {})
54 |
55 | reporter.report(error)
56 | end
57 | end
58 |
59 | context "using the :raven strategy" do
60 | let(:reporter) { described_class.new(:raven) }
61 |
62 | it "Raises an error if the Raven constant is not defined" do
63 | expect { reporter.report(error) }.to raise_error(ApiErrorHandler::MissingDependencyError)
64 | end
65 |
66 | it "Reports to Sentry with an error id" do
67 | stub_const("Raven", double)
68 | expect(Raven).to receive(:capture_exception).with(error, extra: { error_id: "456" })
69 |
70 | reporter.report(error, error_id: "456")
71 | end
72 |
73 | it "Reports to Sentry without an error id" do
74 | stub_const("Raven", double)
75 | expect(Raven).to receive(:capture_exception).with(error, extra: {})
76 |
77 | reporter.report(error)
78 | end
79 | end
80 |
81 | context "using the :sentry strategy" do
82 | let(:reporter) { described_class.new(:sentry) }
83 |
84 | it "Raises an error if the Sentry constant is not defined" do
85 | expect { reporter.report(error) }.to raise_error(ApiErrorHandler::MissingDependencyError)
86 | end
87 |
88 | it "Reports to Sentry with an error id" do
89 | stub_const("Sentry", double)
90 | expect(Sentry).to receive(:capture_exception).with(error, extra: { error_id: "456" })
91 |
92 | reporter.report(error, error_id: "456")
93 | end
94 |
95 | it "Reports to Sentry without an error id" do
96 | stub_const("Sentry", double)
97 | expect(Sentry).to receive(:capture_exception).with(error, extra: {})
98 |
99 | reporter.report(error)
100 | end
101 | end
102 | end
103 |
--------------------------------------------------------------------------------
/spec/api_error_handler/serializers/json_api_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "json"
4 | require_relative "../../../lib/api_error_handler/serializers/json_api"
5 |
6 | RSpec.describe ApiErrorHandler::Serializers::JsonApi do
7 | it "has a render format of :json" do
8 | error = RuntimeError.new("RuntimeError message!")
9 | status = :not_found
10 |
11 | serializer = described_class.new(error, status)
12 |
13 | expect(serializer.render_format).to eq(:json)
14 | end
15 |
16 | describe "#serialize" do
17 | it "renders the error in JSON:API format" do
18 | error = RuntimeError.new("RuntimeError message!")
19 | status = :not_found
20 |
21 | serializer = described_class.new(error, status)
22 |
23 | response = JSON.parse(serializer.serialize, symbolize_names: true)
24 |
25 | expect(response).to eq(
26 | errors: [
27 | { title: "Not Found", detail: "RuntimeError message!", status: "404" }
28 | ]
29 | )
30 | end
31 |
32 | it "includes the backtrace if the backtrace option is true" do
33 | error = nil
34 |
35 | begin
36 | raise "some error"
37 | rescue => e
38 | error = e
39 | end
40 |
41 | status = :not_found
42 |
43 | serializer = described_class.new(error, status)
44 | response = JSON.parse(serializer.serialize(backtrace: true), symbolize_names: true)
45 |
46 | expect(response[:errors].first.dig(:meta, :backtrace)).to eq(error.backtrace)
47 | end
48 | end
49 | end
50 |
--------------------------------------------------------------------------------
/spec/api_error_handler/serializers/json_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "json"
4 | require_relative "../../../lib/api_error_handler/serializers/json"
5 |
6 | RSpec.describe ApiErrorHandler::Serializers::Json do
7 | describe "#serialize" do
8 | it "renders the error in a JSON format" do
9 | error = RuntimeError.new("RuntimeError message!")
10 | status = :not_found
11 |
12 | serializer = described_class.new(error, status)
13 |
14 | response = JSON.parse(serializer.serialize, symbolize_names: true)
15 |
16 | expect(response).to eq(
17 | error: { title: "Not Found", detail: "RuntimeError message!" }
18 | )
19 | end
20 |
21 | it "includes the error id if one is provided" do
22 | error = RuntimeError.new("RuntimeError message!")
23 | status = :not_found
24 |
25 | serializer = described_class.new(error, status)
26 | response = JSON.parse(serializer.serialize(error_id: "123"), symbolize_names: true)
27 |
28 | expect(response.dig(:error, :id)).to eq("123")
29 | end
30 |
31 | it "includes the backtrace if the backtrace option is true" do
32 | begin
33 | raise "some error"
34 | rescue => e
35 | error = e
36 | end
37 |
38 | status = :not_found
39 |
40 | serializer = described_class.new(error, status)
41 | response = JSON.parse(serializer.serialize(backtrace: true), symbolize_names: true)
42 |
43 | expect(response.dig(:error, :backtrace)).to eq(error.backtrace)
44 | end
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/spec/api_error_handler/serializers/xml_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require_relative "../../../lib/api_error_handler/serializers/xml"
4 | require "nokogiri"
5 |
6 | RSpec.describe ApiErrorHandler::Serializers::Xml do
7 | describe "#serialize" do
8 | it "renders the error in a xml format" do
9 | error = RuntimeError.new("RuntimeError message!")
10 |
11 | serializer = described_class.new(error, :not_found)
12 |
13 | expect(serializer.serialize).to eq(<<~XML
14 |
15 |
16 | Not Found
17 | RuntimeError message!
18 |
19 | XML
20 | )
21 | end
22 |
23 | it "includes the error ID if the error_id option is present" do
24 | error = RuntimeError.new("RuntimeError message!")
25 |
26 | serializer = described_class.new(error, :not_found)
27 | response = Hash.from_xml(serializer.serialize(error_id: "567"))
28 |
29 | expect(response.dig("Error", "Id")).to eq("567")
30 | end
31 |
32 | it "includes the backtrace if the backtrace option is true" do
33 | raise "some error"
34 | rescue => e
35 | serializer = described_class.new(e, :not_found)
36 | response = Nokogiri::XML(serializer.serialize(backtrace: true)).xpath("//Backtrace")
37 |
38 | expect(response.inner_text).to eq(e.backtrace.to_s)
39 | end
40 | end
41 | end
42 |
--------------------------------------------------------------------------------
/spec/api_error_handler_spec.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | RSpec.describe ApiErrorHandler do
4 | it "has a version number" do
5 | expect(ApiErrorHandler::VERSION).not_to be nil
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require "bundler/setup"
4 | require "api_error_handler"
5 |
6 | RSpec.configure do |config|
7 | # Enable flags like --only-failures and --next-failure
8 | config.example_status_persistence_file_path = ".rspec_status"
9 |
10 | # Disable RSpec exposing methods globally on `Module` and `main`
11 | config.disable_monkey_patching!
12 |
13 | config.expect_with :rspec do |c|
14 | c.syntax = :expect
15 | end
16 | end
17 |
--------------------------------------------------------------------------------