Tuesday, July 21, 2009

Sending mail to developer about exception errors

I want my application to send me a mail about any errors that occurs during production. Basically, I want to see a detail report like in development environment. All I have to do is to override rescue_action_in_public. This method by default calls render_optional_error_file method to render a static page based on status code thrown. rescue_action_locally method by default will render details diagnostics from a controller action. Therefore, I just combine all of these methods into rescue_action_in_public and add some code to send mail.

def rescue_action_in_public(exception)
   render_optional_error_file response_code_for_rescue(exception)

   @template.instance_variable_set("@exception", exception)
   @template.instance_variable_set("@rescues_path", RESCUES_TEMPLATE_PATH)
   @template.instance_variable_set("@contents",
   @template.render(:file => template_path_for_local_rescue(exception)))

# send mail to developers
   mail = ExceptionNotifier.create_sent(@template)
   mail.set_content_type("text/html")
   ExceptionNotifier.deliver(mail)
end

Here is my ExceptionNotifier class, just extract needed variable to be available inside my view.

class ExceptionNotifier < ActionMailer::Base

   def sent(template)
      @subject = 'Bug Reports'
      @body["request"] = template.request
      @body["response"] = template.response
      @body["exception"] = template.instance_variable_get("@exception")
      @body["rescues_path"] = template.instance_variable_get("@rescues_path")
      @recipients = ['chamnapchhorn@gmail.com', 'ungsophy@gmail.com']
      @from = 'noreply@gmail.com'
      @headers = {}
   end

end

Here is my view, the default view for exception. I just change to locate new variables only.

<h1>
   <%=h @exception.class.to_s %>
      <% if @request.parameters['controller'] %>
         in <%=h @request.parameters['controller'].humanize %>Controller<% if @request.parameters['action'] %>#<%=h @request.parameters['action'] %><% end %>
      <% end %>
</h1>
<pre><%=h @exception.clean_message %></pre>

<%= render :file => @rescues_path["rescues/_trace.erb"] %>

<%= render :file => @rescues_path["rescues/_request_and_response.erb"], :locals => { :request => @request, :response => @response } %>

3 comments:

xalucardx said...

do php for web instant of java

chamnap said...

I don't understand.

Savot Dane said...

Update your blog dude.

Subscribe in a Reader