Toshi
Toshi

Reputation: 6360

Rails 4; Raise an error and catch within controller

I'd love to define a rescue_from handler in my controller to respond to the error.

modudle Api
  module V1
    class TreesController < Api::V1::ApiController
      rescue_from TreeNotFound, with: :missing_tree

       def show
         @tree = find_tree
        end

       private

       def missing_tree(error)
         redirect_to(action: :index, flash: error.message)
        end

       def find_tree
         find_forest.trees.find(params[:id])
       rescue ActiveRecord::RecordNotFound
         raise TreeNotFound, "Couldn't find a tree to hug"
       end
     end
   end
end

However I got some error Api::V1::TreesController::TreeNotFound.

Any idea?

Update

    # api_controller.rb    
    module Api
      module V1
        class ApiController < JSONAPI::ResourceController
          skip_before_action :verify_authenticity_token # Disable CSRF to enable to function as API

          respond_to :json

          # NOTE: This block is used when you put unrelated values
          rescue_from(ArgumentError) do |e|
            render json: { error: e.message }, states: 400 # :bad_request
          end

          rescue_from(ActionController::ParameterMissing) do |e|
            error = {}
            error[e.param] = ['parameter is required']
            response = { errors: [error] }
            render json: response, status: 422 # :unprocessable_entity
          end   
        end
      end
    end

Upvotes: 2

Views: 831

Answers (1)

jvnill
jvnill

Reputation: 29599

you need to declare the error class first before you can use it. Do this by inheriting from StandardError.

class TreeNotFound < StandardError
end

Upvotes: 2

Related Questions