Skip to content

Instantly share code, notes, and snippets.

@mfo
Created April 5, 2013 11:07
Show Gist options
  • Save mfo/5318501 to your computer and use it in GitHub Desktop.
Save mfo/5318501 to your computer and use it in GitHub Desktop.
Looking for an idea for a graceful way to DRY repetition regarding the error rescuing...
class Api::CollectionsController < ApplicationController
def update
@collection = Collection.where(pname: params[:id], event_id: @event.id).first
@collection.assign_to(@event, params[:collection])
@status = @collection.save! ? "ok" : "ko"
render status: 200
rescue Exception => e
@status = "ArgumentError"
@error = @collection.errors.keys
render status: 400
end
def create
@collection = Collection.new_by_type(params[:collection][:type])
@collection.assign_to(@event, params[:collection])
@status = @collection.save! ? "ok" : "ko"
render status: 200
rescue NameError => e
@status = "NameError"
@error = ["type"]
render status: 400
rescue Exception => e
@status = "ArgumentError"
@error = @collection.errors.keys
render status: 400
end
end
@mfo
Copy link
Author

mfo commented Apr 5, 2013

thx to @JohnMeiss for the link : http://stackoverflow.com/questions/8644577/how-to-rescue-exception-central-and-dry

class Api::CollectionsController < ApplicationController
  def update
    rescue_collection_operation do
      @collection = Collection.where(pname: params[:id], event_id: @event.id).first
      @collection.assign_to(@event, params[:collection])

      @status = @collection.save! ? "ok" : "ko"
      render status: 200
    end
  end

  def create
    rescue_collection_operation do
      @collection = Collection.new_by_type(params[:collection][:type])
      @collection.assign_to(@event, params[:collection])

      @status = @collection.save! ? "ok" : "ko"
      render status: 200
    end
  end

  private

  def rescue_collection_operation
    yield
  rescue NameError => e
    @status = "NameError"
    @error = ["type"]
    render status: 400
  rescue Exception => e
    @status = "ArgumentError"
    @error = @collection.errors.keys
    render status: 400
  end
end

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