Error Handling — Modular Approach
1.
app/controllers/application_controller.rb
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 include Error::ErrorHandler end
error
handling blocks. It looks much cleaner this way.
lib/error/error_handler.rb
#
Error module to Handle errors globally
# include Error::ErrorHandler in
application_controller.rb
# Refactored ErrorHandler to handle multiple errors # Rescue StandardError acts as a Fallback mechanism to handle any exception module Error module ErrorHandler def self.included(clazz) clazz.class_eval do rescue_from ActiveRecord::RecordNotFound do |e| respond(:record_not_found, 404, e.to_s) end rescue_from StandardError do |e| respond(:standard_error, 500, e.to_s) end end end private def respond(_error, _status, _message) json = Helpers::Render.json(_error, _status, _message) render json: json end end end
3.
Define your own Exception (lib/error/custom_error.rb)
module
Error
class CustomError < StandardError attr_reader :status, :error, :message def initialize(_error=nil, _status=nil, _message=nil) @error = _error || 422 @status = _status || :unprocessable_entity @message = _message || 'Something went wrong' end def fetch_json Helpers::Render.json(error, message, status) end end end
Custom
Error File Name:- (lib/error/not_visible_error.rb)
module
Error
class NotVisibleError < CustomError def initialize super(:you_cant_see_me, 422, 'You can\'t see me') end end end
You
can handle common exceptions like 404 and 500, although it’s
totally up to the developer. We need to create a separate controller
class, ErrorsController for it.
Error
Controller File Name:-(controllers/errors_controller.rb)
class ErrorsController < ApplicationController def not_found render json: { status: 404, error: :not_found, message: 'Where did the 403 errors go' }, status: 404 end def internal_server_error render json: { status: 500, error: :internal_server_error, message: 'Houston we have a problem' }, status: 500 end end
5.
We
just have to add the following line to application.rb.
config.exceptions_app = routes
6. Tell Rails to use Routes to resolve exceptions. Rails.application.routes.draw do get '/404', to: 'errors#not_found' get '/500', to: 'errors#internal_server_error' root 'home#index' get 'not_visible', to: 'home#not_visible' end Now 404 exceptions fallback to errors#not_found and 500 to errors#internal_server_error. Error Handling Link:- https://medium.com/rails-ember-beyond/error-handling-in-rails-the-modular-way-9afcddd2fe1b