Error Checking and Debugging with Ruby on Rails (Page 1 of 4 )
15.20 Automatically Sending Error Messages to Your Email
You want to receive a descriptive email message every time one of your users encounters an application error.
Any errors that occur while running your application are sent to the ActionController::Base#log_error method. If you've set up a mailer (as shown in Recipe 15.19) you can override this method and have it send mail to you. Your code should look something like this:
class ApplicationController < ActionController::Base
private def log_error(exception) super Notification.deliver_error_message(exception, clean_backtrace(exception), session.instance_variable_get("@data"), params, request.env ) end end
That code rounds up a wide variety of information about the state of the Rails request at the time of the failure. It captures the exception object, the corresponding backtrace, the session data, the CGI request parameters, and the values of all environment variables.
The overridden log_error calls Notification.deliver_error_messsage, which assumes you've created a mailer called "Notification", and defined the method Notification.error_message. Here's the implementation:
Params <% @params.each do |key, val| -%> * <%= key %>: <%= val.to_yaml %> <% end -%>
Session <% @session.each do |key, val| -%> * <%= key %>: <%= val.to_yaml %> <% end -%>
Environment <% @env.each do |key, val| -%> * <%= key %>: <%= val %> <% end -%>
ActionController::Base#log_error gives you the flexibility to handle errors however you like. This is especially useful if your Rails application is hosted on a machine to which you have limited access: you can have errors sent to you, instead of written to a file you might not be able to see. Or you might prefer to record the errors in a database, so that you can look for patterns.
The method ApplicationController#log_error is declared private to avoid confusion. If it weren't private, all of the controllers would think they had a log_error action defined. Users would be able to visit /<controller>/log_error and get Rails to act strangely.