Skip to content
Hugh Francis edited this page Aug 3, 2015 · 1 revision

The first thing you'll want to do is setup some APPI style exception handling in your application. This is a snap!

In your application_controller.rb:

module YourAPI
  class ApplicationController < ActionController::Base
    include APPI::RendersExceptions
  
    rescue_from APPI::Exception do |exception|
      render_appi_exception exception 
    end

  end
end

Now, whenever you need to show the user an error, you can do something like this:

module YourAPI
  class PostsController < ApplicationController
  
    def update
      unless params[:can_update]
        raise APPI::Exception.new("posts.will_not_update", id: @post.id)
      end
      ...
    end

  end
end

Then in your Rails i18n locale:

# config/locales/en.yml

en:
  appi_exceptions:
    posts:
      will_not_update: 
        title: 'Posts: Could Not Save'
        detail: 'Could not update a post with ID: %{id}.
        status: 'unprocessable_entity'

You can handle External & Rails exceptions with APPI too:

class ApplicationController < ActionController::Base
  include APPI::RendersExceptions

  rescue_from Exception do |exception|
    case exception
    when APPI::Exception
      render_appi_exception exception 

    when CanCan::AccessDenied
      details = {
        action: exception.action.to_s
      }

      if exception.subject.respond_to? :id
        details[:subject_id]         = exception.subject.id.to_s
        details[:subject_class_name] = exception.subject.class.to_s 
      else
        details[:subject_id]         = nil
        details[:subject_class_name] = exception.subject.to_s
      end

      render_appi_exception APPI::Exception.new('permissions.access_denied', details)

    else
      render_appi_exception APPI::Exception.new('rails.untracked_error', message: exception.message)
    end
  end
end