Skip to content

Instantly share code, notes, and snippets.

@dmytrotkk
Created November 8, 2017 14:42
Show Gist options
  • Save dmytrotkk/3109b5a6029868a0515d5af089fd6ec2 to your computer and use it in GitHub Desktop.
Save dmytrotkk/3109b5a6029868a0515d5af089fd6ec2 to your computer and use it in GitHub Desktop.
Handling errors in Rails with ActiveSupport

Handling errors in Rails with ActiveSupport

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 and Proc's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment