Instantly share code, notes, and snippets.

Embed
What would you like to do?
404, 500 Errors huddling
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
if Rails.env.production? || Rails.env.staging?
# 他のエラーハンドリングでキャッチできなかった場合に
# 500 Internal Server Error(システムエラー)を発生させる
rescue_from Exception, with: :handle_500
# 例外に合わせたエラーハンドリング
# 404 Not Found リソースが見つからない。アクセス権がない場合にも使用される
rescue_from ActionController::RoutingError, with: :handle_404
rescue_from ActiveRecord::RecordNotFound, with: :handle_404
end
# エラーハンドリング処理
def handle_500(exception = nil)
logger.info "Rendering 500 with exception: #{exception.message}" if exception
ExceptionNotifier.notify_exception(exception, :env => request.env, :data => {:message => exception.message})
if request.xhr?
render json: { error: '500 error' }, status: 500
else
render 'errors/error_500.html', layout: 'default', status: 500, content_type: 'text/html'
end
end
def handle_404(exception = nil)
logger.info "Rendering 404 with exception: #{exception.message}" if exception
if request.xhr?
render json: { error: '404 error' }, status: 404
else
render 'errors/error_404.html', status: 404, layout: 'default', content_type: 'text/html'
end
end
:
:
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment