Rails provide a clean way to rescue exceptions in a controller with a defined method.
Let's suppose that you have a class with method create
that could raise ActiveRecord::RecordInvalid
exception:
class ExampleController < ApplicationController
def create
item = User.new(user_params)
item.validate! # this could raise an exception
# ....
end
end
We could add rescue for this exception at the action level (in the create
method), but isn't it would be prettier to instruct the controller to rescue all the ActiveRecord::RecordInvalid
exceptions and trigger a corresponding method? So, we'll do.
class ExampleController < ApplicationController
rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response
def render_unprocessable_entity_response(exception)
render json: exception.record.errors, status: :unprocessable_entity
end
# ...
def create
item = User.new(user_params)
item.validate! # this could raise an exception
# ....
end
end
Now if validation line will fail with RecordInvalid
exception it will be rescued with render_unprocessable_entity_response
.
Note: The rescue_from method also accepts
block
's andProc
's.