Handling Errors and Failures in Rails – Turing



Handling Errors and Failures in Rails – Turing

0 0


handling-errors-intro


On Github jxandery / handling-errors-intro

Handling Errors and Failures in Rails

Turing

Osama Alghanmi / @itechdom

Learning Goals

  • Learn How to handle errors in Rails
  • Implement your own error controller to create custom error views
  • Handle ActiveRecord Exceptions

Structure

  • 10 - Warmup and Discussion
  • 10 - Why should we handle our own erros
  • 5 - Break
  • 10 - Active Record Rescue
  • 15 - Setup
  • 5 - Break
  • 20 - Exercise
  • 15 - Recap and Discussion

Why

  • Rails handles some basic errors, like 404 and 500.
  • However, if you want to make your app more resilient, you should handle your own errors.
  • You can rescue routing errors, and active record errors giving you more flexibility.
  • To test this, you need a development environment that resembles production, but gives you the safety net to experiment.

Rescue in Active_records

  • We use the block
rescue ActiveRecord::RecordNotFound
    # you put your code here to rediret
end

Setup

How to create a staging environment

  • Create a staging.rb file in the environments folder.

  • Copy the contents of the production.rb.

  • Set the config.log_level to debug.

  • Add staging to Gemfile

  • Add the database configuration for the staging server.

  • Set the staging database:

RAILS_ENV=staging rake db:migrate
  • Run rake assets:precompile
RAILS_ENV=staging rake assets:precompile

How to handle routing exceptions

  • Add this route to the end of your routes.rb
    get '*path', :to => 'errors#show'
  • Create an Errors Controller
  • Create a show action in the errors controller: render template
  • Add 404.html.erb template to the errors/views

Handling ActiveRecord Exceptions

  • Open the show action in the user controller
  • Use begin and rescue to rescue ActiveRecord::RecordNotFound and redirect to users_path
  • Use rescue_from ActiveRecord::RecordNotFound, with: :record_not_found. Create a private method that redirects_to users_path, notice: 'The users you are looking for doesn’t exist'
  • it’s not ok to rescue all errors, such as validations.

Exercise

  • Scaffold a Course controller.
  • Run migrations, remember to set the database in Staging.
  • Create a show action in the course controller that finds a particular course.
  • Create the view.
  • In the show action, rescue a record not found error and redirect to the course#index.

Recap

  • Create a Staging Environment
  • Handling Routing Exceptions
  • Handling ActiveRecord Exceptions