Skip to content

Instantly share code, notes, and snippets.

@cknoxrun
Created July 8, 2013 21:45
Show Gist options
  • Save cknoxrun/5952765 to your computer and use it in GitHub Desktop.
Save cknoxrun/5952765 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
# Render 404: Not Found
def render_404(exception = nil)
logger.info( clean_backtrace(exception, "Rendering 404 due to exception") )
if /(jpe?g|png|gif)/i === request.path
# Images should simply return the error as text
return render(text: "404 Not Found", status: 404 )
end
render_error(404, "Resource Not Found")
end
protected
def render_error(code, message)
respond_to do |format|
format.html { render :template => "/errors/#{code}", :layout => 'application', :status => code }
format.json { render json: { error: message }, status: code }
format.xml { render xml: { error: message }, status: code }
format.any { render nothing: true, status: code }
end
true # so we can do "render_xxx and return"
end
# Returns a "clean" backtrace that is suitable for humans
def clean_backtrace(exception, preamble="Caught Exception")
"\n\n#{preamble}:" + "\n\n#{exception.class} (#{exception.message}):\n " +
Rails.backtrace_cleaner.clean(exception.backtrace).join("\n ") + "\n\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment