Merb exception email notifier
1. Handle internal_server_error in your exceptions controller. Deliver email before render.
In app/controllers/exceptions.rb:
class Exceptions < Merb::Controller ... cattr_accessor :email_addresses def internal_server_error @exception = self.params[:exception] @exception_name = @exception.name.split("_").map {|x| x.capitalize}.join(" ") notify_emails if Merb.env?(:production) render end private def notify_emails begin return if self.class.email_addresses.blank? subject = "[#{@exception.class::STATUS}] #{@exception_name}: #{@exception.message}" mail_body = render(:template => "exceptions/error_email.txt") email = Merb::Mailer.new({ :to => self.class.email_addresses.join(", "), :from => "MyApp", :subject => subject, :text => mail_body }) email.deliver! rescue Error => e Merb.logger.error("Error sending error email: #{e}") end end end
2. Define your email template.
In app/views/exceptions/error_email.txt.rb:
<%= @exception_name %> (<%= @exception.class::STATUS %>): <%= @exception.message %> URL: <%= "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" %> Parameters: <%= params[:original_params].inspect %> <% @exception.backtrace.each_with_index do |line, index| %> <%= (line.match(/^([^:]+)/)[1] rescue 'unknown').sub(/\/((opt|usr)\/local\/lib\/(ruby\/)?(gems\/)?(1.8\/)?(gems\/)?|.+\/app\/)/, '') %>:<%=line%> <% end %>
3. Configure the mailer. This example uses sendmail.
In config/init.rb:
dependency "merb-mailer" Merb::BootLoader.after_app_loads do ... # Mailer configuration Merb::Mailer.config = {:sendmail_path => "/usr/sbin/sendmail"} Merb::Mailer.delivery_method = :sendmail Exceptions.email_addresses = ["my@email.com"] end
If you need something more complex, there is a merb_exceptions plugin from newbamboo.
May 13th, 2008 at 8:26 pm
Be VERY careful when you’re writing these. If your templates have syntax errors you won’t get your mails(or an exception telling you about it), and it’s a royal pain in the ass to track down.
I want those few hours back.
May 13th, 2008 at 8:26 pm
Hi, very useful this, can we port it to a Merb Slice?