Global Error Catching
To handle errors globally in your application, add..
<typo:code lang="ruby">
(within application.rb)
def rescue_action_in_public(exception)
render :text => "<html><body><p>
There was a global error processing your request.</p>
<!-- #{exception} --></body></html>"
end
def local_request?
false
end
</typo:code>
The final def def local_request? tells rails that it should act the same way in development mode.
Local Error Catching
To catch errors locally within your form submits do...
<typo:code lang="ruby">
def update
return unless request.post?
begin
User.update(self.current_user.id, params[:user])
render :action => 'success'
rescue ActiveRecord::RecordInvalid
flash[:notice] = "Sorry, your profile was not saved"
render :action => 'profile'
rescue
flash[:notice] = "Sorry, something went wrong"
render :action => 'profile'
end
end
</typo:code>
Simple process, here we're basically saying if the user has submitted form data (done a POST), then process the code; if not redirect back to the sending page.
If yes then update the User object relevant to the specific user record (found by the id), updating the record with the parameters from the form. Save the record and render the 'success' page.
If we get a problem with saving the record (activerecord), display a message and goto the 'profile' page.
If we get some other error, display the second message and goto the 'profile' page.
Notify Me of Errors via Email
On top of this you can enhance it with flash messages and send off an email with the error code, here's one such way.
<typo:code lang="ruby">
(in application.rb)
protected
def log_error(exception)
super(exception)
begin
Alert.deliver_errormail(
exception,
clean_backtrace(exception),
@session.instance_variable_get("@data"),
@params,
@request.env)
rescue => e
logger.error(e)
end
end
</typo:code>
Adding this makes it send error emails in development mode..
<typo:code lang="ruby">
def local_request?
false
end
</typo:code>
Now create an Mailer object with...
<typo:code lang="xml">
script/generate mailer Alert
</typo:code>
And put this code in your generated alert.rb file
<typo:code lang="ruby">
class Alert < ActionMailer::Base
def errormail(exception, trace, session, params, env, sent_on = Time.now)
content_type "text/html"
@recipients = 'john@gmail.com'
@from = 'admin@mysite.com'
@subject = "[Error] exception in #{env['REQUEST_URI']}"
@sent_on = sent_on
@body["exception"] = exception
@body["trace"] = trace
@body["session"] = session
@body["params"] = params
@body["env"] = env
end
end
</typo:code>
And create a appropriate alert/errormail.rhtml file in your view for the formatted error email...
<typo:code lang="ruby">
<!--
* { font-size: 9pt; font-family: verdana, helvetica, arial, sans-serif; line-height: 1.7em; }
p { margin: 0 }
-->
Error report from <%= Time.now %>
| Message | <%= @exception.message %> |
| Location | <%= @env['REQUEST_URI'] %> |
| Action | <%= @params.delete('action') %> |
| Controller | <%= @params.delete('controller') %> |
| Query | <%= @env['QUERY_STRING'] %> |
| Method | <%= @env['REQUEST_METHOD'] %> |
| SSL | <%= @env['SERVER_PORT'].to_i == 443 ? "true" : "false" %> |
| Agent | <%= @env['HTTP_USER_AGENT'] %> |
<% if @session['user'] -%>
| User id | <%= @session['user'].id %> |
| User name | <%= @session['user'].name %> |
| User email | <%= @session['user'].email %> |
| Registered | <%= @session['user'].created_at %> |
<% end -%>
Backtrace
<%= @trace.to_a.join("\n
") -%>
Params
<% for key, val in @params -%>
<%= key %>
<%= val.to_yaml.to_a.join("
\n
") %>
<% end if @params -%>
Session
<% for key, val in @session -%>
<%= key %>
<%= val.to_yaml.to_a.join("
\n
") %>
<% end if @session -%>
Environment
<% for key, val in @env -%>
|
<%= key %>
|
<%= val %>
|
<% end if @env -%>
</typo:code>
Now whenever an error happens you'll get an email about it, good for the production environment.
Setup the Emailer
Remember to setup the emailer otherwise no emails will be sent.
By adding this to your environments/production.rb
<typo:code lang="ruby">
config.action_mailer.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
</typo:code>
Or more detailed,
Setup a DNS MX Record so you don't get blacklisted!
A further note, remember to add an MX record for the domain your using otherwise your site will be blacklisted by anti-spam sites.
An MX record basically tells other sites where they should send emails to, it's like saying where the postman should deliver incoming letters.
Now if your only sending emails you shouldn't need this but as a previous commenter noted, most anti-spam sites blacklist you if your sending and don't have one; regardless of whether you want the site to receive emails or not. Hence you've got to include one.
A simple example is...
<typo:code lang="xml">
type: MX
name: mysite.com
data: ASPMX.L.GOOGLE.COM.
auxilary info: 1
</typo:code>
Now ok, this is actually telling anti-spammers your using Google Applications to handle your email (which isn't strictly true) but at least it get's them off your back until you setup your own full-blown POSTFIX mail server.
Which is something I'm working on writing an article for.
Expect that in a future posting.