[ruby-it] gestione eccezioni -> best practice
Simone Carletti
weppos a gmail.com
Mar 4 Ago 2009 11:38:45 CEST
Personalmente uso le eccezioni molto spesso.
Li preferisco anche all'uso dei vari if nelle azioni CRUD.
Ecco un esempio che dovrebbe rispondere anche alla tua domanda.
def create
@domain = Domain.new(params[:domain])
@domain.save!
flash[:notice] = 'Domain was successfully created'
respond_to do |format|
format.html { redirect_to(@domain) }
format.xml { render :xml => @domain, :status => :created, :location =>
@domain }
end
rescue ActiveRecord::RecordInvalid
respond_to do |format|
format.html { render :action => "new" }
format.xml { render :xml => @domain.errors, :status =>
:unprocessable_entity }
end
end
Ecco un esempio invece più complesso che usa anche il rescue_from.
class MyController < ApplicationController
rescue_from RoboNet::Whois::Error, :with => :error
rescue_from Hostname::InvalidHostnameError, :with => :error
def run
@hostname = Hostname.fetch(params[:qstring])
@response = @hostname.query_whois
respond_to do |format|
format.html
format.js { render :layout => false }
end
rescue Timeout::Error
raise RoboNet::Whois::Error, "Execution timed out. The server tooks to
long to respond."
# TODO: move into RoboNet class to avoid re-thrown
rescue ::Whois::Error => e
raise RoboNet::Whois::Error, e.message
end
end
Sono esempi live estratti da reali applicazioni, consiglio di vedere la
logica più che il codice in sé.
Il secondo caso merita particolare attenzione perché sfrutta decisamente a
fondo il sistema di convenzioni built-in in Rails.
-- Simone
2009/8/4 Mattia Lipreri <mattia.lipreri a gmail.com>
> Grazie della dritta, ma non ho ancora ben chiaro come gestire le
> eccezione del tipo ActiveRecord::RecordNotFound o
> ActiveRecord::RecordInvalid...in questo caso mi basterebbe segnalare che
> qualcosa è andato storto all'utente, come potrei fare?
> Grazie
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Ml mailing list
> Ml a lists.ruby-it.org
> http://lists.ruby-it.org/mailman/listinfo/ml
>
--
Simone Carletti
Site & Blog: http://www.simonecarletti.com
Email: weppos a weppos.net
LinkedIn: http://linkedin.com/in/weppos
Nick: weppos | Skype: weppos
More information about the Ml
mailing list