Class: Rack::EmailErrors

Inherits:
Object show all
Defined in:
lib/kiss/rack/email_errors.rb

Overview

Rack::EmailErrors sends error responses (code 5xx) to email addresses as specified in the Rack::Builder config.

Instance Method Summary collapse

Constructor Details

#initialize(app, *args) ⇒ EmailErrors

Returns a new instance of EmailErrors.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/kiss/rack/email_errors.rb', line 8

def initialize(app, *args)
  @_app = app
  
  if (options = args.first).is_a?(Hash)
    @_agent = options[:agent]
    @_subject = options[:subject]
    @_from = options[:from]
    @_to = options[:to]
  else
    @_agent, @_subject, @_from, *@_to = *args
  end
  
  @_agent = '/usr/sbin/sendmail -t' if @_agent == :sendmail
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kiss/rack/email_errors.rb', line 23

def call(env)
  code, headers, body = @_app.call(env)
  
  if code >= 500 && code < 600
    begin # rescue any errors in message composition and sending
      error_type = headers['X-Kiss-Error-Type'] || "#{code} Error"
      error_message = headers['X-Kiss-Error-Message']
      
      message = <<-EOT
Content-type: text/html
From: #{@_from}
To: #{@_to.join(', ')}
Subject: #{@_subject} - #{error_type}#{ error_message ? ": #{error_message}" : ''}

EOT
      
      body.each do |part|
        message += part
      end
      
      if @_agent.is_a?(String)
        IO.popen(@_agent, "w") do |pipe|
          pipe.puts(message)
        end
      else
        require 'net/smtp' unless defined?(Net::SMTP)
        smtp = @_agent.is_a?(Net::SMTP) ? @_agent : Net::SMTP.new('localhost')
        smtp.start do |smtp|
      		smtp.send_message(message, @_from, *@_to)
      	end
    	end
    rescue
    end
    
    body = <<-EOT
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Application Server Error</h1>
<p>Sorry, an error occurred.  Our technical staff has been notified and will investigate this issue.</p>
</body>
</html>
EOT
    headers['Content-Length'] = body.content_length.to_s
  end
  
  [ code, headers, body ]
end