Created
July 18, 2014 09:19
-
-
Save eLafo/a4f0fcdbfd1e4ada5c53 to your computer and use it in GitHub Desktop.
Concern exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Exceptions | |
extend ActiveSupport::Concern | |
included do | |
unless Rails.application.config.consider_all_requests_local | |
rescue_from Exception, with: :render_error | |
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found | |
rescue_from ActionController::RoutingError, with: :render_not_found | |
rescue_from ActionController::UnknownController, with: :render_not_found | |
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized | |
rescue_from ActionController::UnknownFormat, with: :render_not_found | |
end | |
rescue_from NoMembershipError, with: :select_course | |
end | |
# Called by last route matching unmatched routes | |
# Raises RoutingError which will be rescued from in the same way as other exceptions. | |
def raise_not_found! | |
render nothing: true and return if params[:path] && params[:path] =~ /\A(assets|uploads|images)/ | |
raise ActionController::RoutingError.new("No route matches #{params[:path]}") | |
end | |
private | |
def select_course | |
if current_user.courses.ongoing.blank? | |
redirect_to new_contact_path and return | |
else | |
redirect_to courses_path and return | |
end | |
end | |
def render_not_found(exception) | |
render_exception exception, code: 404, message: 'Not Found Error' | |
end | |
def render_error(exception) | |
render_exception exception, code: 500, message: 'Server Error' | |
end | |
def user_not_authorized(exception) | |
render_exception exception, code: 403, message: 'Not Authorized' | |
end | |
def render_exception(exception, opts = {}) | |
Rails.logger.info exception.message | |
Rails.logger.info exception.backtrace.join("\n") | |
#Rollbar.report_exception(exception, rollbar_request_data, rollbar_person_data) | |
respond_to do |format| | |
format.html { render layout: 'application', template: "application/#{opts[:code]}", status: opts[:code] } | |
format.js { render json: { error: opts[:message] }, status: opts[:code] } | |
format.json { render json: { error: opts[:message] }, status: opts[:code] } | |
end | |
end | |
class NoMembershipError < StandardError | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment