Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Exceções com Ruby on Rails

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for brunnogomes brunnogomes
February 22, 2014

Exceções com Ruby on Rails

Vamos falar um pouco sobre o tratamento de exceções em Ruby, porque os programadores Rails não usam muito e o que pode dar errado. Além disso mostro alguns exemplos de como você pode tratar exceções utilizando o Rails Way.

Avatar for brunnogomes

brunnogomes

February 22, 2014
Tweet

More Decks by brunnogomes

Other Decks in Programming

Transcript

  1. Exceções “O tratamento de exceção é o mecanismo responsável pelo

    tratamento da ocorrência de condições que alteram o fluxo normal da execução de programas de computadores.” - Wikipedia
  2. O que pode dar errado? class PagesController < ApplicationController def

    create @page = Page.find_or_create_by(title: params[:title]) @page.attributes = params[:page] flash.notice = “Sucesso!” if @page.save respond_with @page end end
  3. O que pode dar errado? class PagesController < ApplicationController def

    show @page = Page.find_or_create_by(title: params[:title]) respond_with @page end end
  4. O que pode dar errado? Documentação: Whether that is a

    problem or not depends on the logic of the application, but in the particular case in which rows have a UNIQUE constraint an exception may be raised…
  5. Tratamento class PagesController < ApplicationController def show @page = Page.find_or_create_by(title:

    params[:title]) respond_with @page rescue # não precisa fazer nada end end
  6. Usando o Log class PagesController < ApplicationController def create @page

    = AwesomePageCreator.create(params[:page]) respond_with @page rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } end end
  7. Usando o Log class PagesController < ApplicationController def create @page

    = AwesomePageCreator.create(params[:page]) respond_with @page rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } Rollbar.report_exception(e) # interface comum end end
  8. Rack App # application.rb ... config.exceptions_app = self.routes ... #

    routes.rb ... match '/404' => 'errors#not_found', via: :all match '/406' => 'errors#not_acceptable', via: :all match '/500' => 'errors#internal_server_error', via: :all ...
  9. Referências / Leitura Recomendada Writing Robust Web Applications - The

    Lost Art of Exception Handling - Alan Skorkin [http://code.tutsplus.com/articles/writing-robust-web- applications-the-lost-art-of-exception-handling--net-36395] How to Write Good Error Messages - Brad Bollenbach [http://bugroll.com/how-to-write-good-error-messages.html]