Created
March 22, 2023 17:37
-
-
Save chrisconcepcion/b8b8d9bfb2a5c1bf7c202390fb3e601f to your computer and use it in GitHub Desktop.
Helpful Debugging Tips for Ruby on Rails
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
class ApplicationController < ActionController::Base | |
def log_error error_message | |
# Defining our log file path, can be named or located anywhere. | |
log_file_path = "#{Rails.root}/log/exception.log" | |
# Check if our log file exists. | |
file_available = File.exist? log_file_path | |
# Create log file if not available. | |
if file_available == false | |
Logger.new(log_file_path) | |
end | |
# Open and append our error message to log file. | |
# NOTE: "a" stands for append mode | |
File.open(log_file_path, "a") do |f| | |
f.puts Time.now | |
f.puts error_message | |
end | |
end | |
end | |
class ItemsController | |
def show | |
# Instance variables will return nil regardless even when undeclared, just demonstrating what to expect | |
# when an item is not found. | |
@item = nil | |
begin | |
# When item is not nil, it will throw an internal server error unless be wrap this find in a b/r/e(begin, rescue, end). | |
# Internal server error is not attractive to users and often when they see errors, they can stop using the product entirely. | |
@item = Item.find(params[:id]) | |
rescue Exception => exception | |
# Log expection. | |
# It's important to log enough data to reproduce a problem. | |
# Also be warned if any of the variables like params or current_user is not available, nothing will be logged | |
# and the server will return a 500 error. | |
log_error "Error found in ItemsController#show. params: #{params}, user_id: #{current_user.id}, exception: #{exception}" | |
# Freeze code exection. | |
# Would be helpful to find where the code specifically field while pry is active. You can figure this out by doing exception.backtrace | |
# and it will return the call stack(file and methods used that led to this error). | |
# You would remove this pry in production right before code review. | |
# Pry gem can documentation can be found here: https://github.com/pry/pry | |
binding.pry | |
end | |
if @item == nil | |
flash[:notice] = "Item has not been found." | |
redirect_to :index | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment