Class: HaveAPI::Extensions::ExceptionMailer

Inherits:
Base
  • Object
show all
Defined in:
lib/haveapi/extensions/exception_mailer.rb

Overview

This extension mails exceptions raised during action execution and description construction to specified e-mail address.

The template is based on Sinatra::ShowExceptions::TEMPLATE, but the JavaScript functions are removed, since e-mail doesn't support it. HaveAPI-specific content is added. Some helper methods are taken either from Sinatra or Rack.

Instance Method Summary collapse

Methods inherited from Base

enabled

Constructor Details

#initialize(opts) ⇒ ExceptionMailer

Returns a new instance of ExceptionMailer.

Parameters:

  • opts (Hash) —

    options

Options Hash (opts):

  • to (String) —

    recipient address

  • from (String) —

    sender address

  • subject (String) —

    '%s' is replaced by the error message

  • smtp (Hash, falsy) —

    smtp options, sendmail is used if not provided



17
18
19
# File 'lib/haveapi/extensions/exception_mailer.rb', line 17

def initialize(opts)
  @opts = opts
end

Instance Method Details

#enabled(server) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/haveapi/extensions/exception_mailer.rb', line 21

def enabled(server)
  HaveAPI::Action.connect_hook(:exec_exception) do |ret, context, e|
    log(context, e)
    ret
  end

  server.connect_hook(:description_exception) do |ret, context, e|
    log(context, e)
    ret
  end
end

#log(context, exception) ⇒ Object



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
# File 'lib/haveapi/extensions/exception_mailer.rb', line 33

def log(context, exception)
  req = context.request.request
  path = (req.script_name + req.path_info).squeeze("/")

  frames = exception.backtrace.map { |line|
    frame = OpenStruct.new

    if line =~ /(.*?):(\d+)(:in `(.*)')?/
      frame.filename = $1
      frame.lineno = $2.to_i
      frame.function = $4

      begin
        lineno = frame.lineno-1
        lines = ::File.readlines(frame.filename)
        frame.context_line = lines[lineno].chomp
      rescue
      end

      frame
    else
      nil
    end
  }.compact

  env = context.request.env

  mail(context, exception, TEMPLATE.result(binding))
end

#mail(context, exception, body) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/haveapi/extensions/exception_mailer.rb', line 63

def mail(context, exception, body)
  mail = ::Mail.new({
    from: @opts[:from],
    to: @opts[:to],
    subject: @opts[:subject] % [exception.to_s],
    body: body,
    content_type: 'text/html; charset=UTF-8',
  })

  if @opts[:smtp]
    mail.delivery_method(:smtp, @opts[:smtp])

  else
    mail.delivery_method(:sendmail)
  end

  mail.deliver!
  mail
end