Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from mashiro/render_error.rb
Created June 22, 2014 21:55
Show Gist options
  • Save kivanio/7e71109b0d31a299424b to your computer and use it in GitHub Desktop.
Save kivanio/7e71109b0d31a299424b to your computer and use it in GitHub Desktop.
module RenderError
extend ActiveSupport::Concern
included do
rescue_from HTTPError do |e|
render_error e.status_code, e.message
end
end
class HTTPError < StandardError
attr_accessor :status_code
def initialize(status, message = nil)
@status_code = Rack::Utils.status_code status
super message || Rack::Utils::HTTP_STATUS_CODES[@status_code]
end
end
def render_error(status, message = nil)
status_code = Rack::Utils.status_code status
message ||= Rack::Utils::HTTP_STATUS_CODES[status_code]
body = {:status => status_code, :message => message}
respond_to do |format|
format.json { render :json => body, :status => status_code }
format.xml { render :xml => body, :status => status_code }
end
end
def error!(status, message = nil)
raise HTTPError.new status, message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment