Skip to content

Commit 8a0252b

Browse files
committed
Add wrapping of ActiveRecord::RecordNotFound
We intend for resources to be pre-checked via `verify_scoped_resource`. However, there are still race conditions which can causes resources to not be found after the check. We do not yet have a mechanism for defining custom scoping for a resource. So some controllers may perform their own custom scoping which can raise a not found error. To handle this we insert our own `rescue_from` clause into all JSON api controllers. This allows us to parse the message and convert it into our standard `ResourceNotFound` error. Our naming convention for resources is underscore names and to be plural. Since AR just puts the model name in the message we need to do the conversion here before creating our custom error.
1 parent abc65c7 commit 8a0252b

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

lib/kracken/controllers/json_api_compatible.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,18 @@ def self.included(base)
119119

120120
before_action :munge_chained_param_ids!
121121
skip_before_action :verify_authenticity_token
122+
123+
if defined?(::ActiveRecord)
124+
rescue_from ::ActiveRecord::RecordNotFound do |error|
125+
# In order to use named captures we need to use an inline regex
126+
# on the LHS.
127+
#
128+
# Source: http://rubular.com/r/NoQ4SZMav4
129+
/Couldn't find( all)? (?<resource>\w+) with 'id'.?( \()?(?<ids>[,\s\w]+)\)?/ =~ error.message
130+
resource = resource.underscore.pluralize
131+
raise ResourceNotFound.new(resource, ids.strip)
132+
end
133+
end
122134
end
123135
end
124136

0 commit comments

Comments
 (0)