Jeremy Thomas
Jeremy Thomas

Reputation: 6684

Rails 4: Using an exception handler module in API controller

I am trying to use an exception handler in my controller but it doesn't seem to be doing anything:

class API::PaymentsController < ApplicationController
    before_filter :set_client

    def index
        @foo = @client.foo
    end

    ...

    def set_client

      rescue ActiveRecord::RecordNotFound do |e|
        render json: e.message, status: :not_found
      end

      @client = Client.find(params[:client_id])
    end
end

and when I go to localhost:3000/clients/[invalid_id]/payments, I still see the error:

ActiveRecord::RecordNotFound (Couldn't find Client with 'id'=1):
app/controllers/payments_controller.rb:58:in `set_client'

when I'd expect the RecordNotFound handler to handle this exception. What am I missing?

Upvotes: 0

Views: 331

Answers (1)

Anurag Aryan
Anurag Aryan

Reputation: 651

The rescue block comes after the failure.

def set_client
  @client = Client.find(params[:client_id])
rescue ActiveRecord::RecordNotFound => err
  render json: { message: err.message}, status: :not_found
end

Upvotes: 1

Related Questions