Handling Postmark Errors

A guide to handling Postmark bounce errors and sending custom notifications using LogStruct.

Error Handling Methods

LogStruct provides three error handling methods you can use in rescue_from handlers:

  • log_and_ignore_error(error) - Logs the error but doesn't report to Sentry or reraise
  • log_and_report_error(error) - Logs the error, reports to Sentry, but doesn't reraise
  • log_and_reraise_error(error) - Logs the error, reports to Sentry, and reraises (for retry)

Example: Handling Postmark Bounce Errors

When using Postmark, you may want to handle bounce errors (inactive recipients, invalid emails) differently than other errors:

# config/initializers/action_mailer_postmark_errors.rb
Rails.application.config.after_initialize do
  ActiveSupport.on_load(:action_mailer) do
    if defined?(Postmark)
      # Postmark bounce errors - log but don't reraise (can't be retried)
      rescue_from Postmark::InactiveRecipientError, with: :log_and_ignore_error
      rescue_from Postmark::InvalidEmailRequestError, with: :log_and_ignore_error
    end
  end
end

Custom Notifications (e.g., Slack)

LogStruct logs structured error data but doesn't send notifications directly. To send custom notifications (like Slack alerts), subscribe to LogStruct logs:

# config/initializers/mailer_notifications.rb
Rails.application.config.after_initialize do
  # Subscribe to LogStruct logs
  ActiveSupport::Notifications.subscribe('log.logstruct') do |_name, _start, _finish, _id, payload|
    log = payload[:log]

    # Send Slack notification for Postmark errors
    if log.is_a?(LogStruct::Log::ActionMailer::Error) &&
       [Postmark::InactiveRecipientError, Postmark::InvalidEmailRequestError].include?(log.error_class)

      InternalSlackNotificationJob.perform_async(
        channel: '#alerts',
        text: "Email delivery error: #{log.message}"
      )
    end
  end
end

Error Log Structure

When a mailer error occurs, LogStruct creates a LogStruct::Log::ActionMailer::Error with:

  • error_class - The exception class (e.g., Postmark::InactiveRecipientError)
  • message - Formatted message including context and the actual exception message
  • backtrace - Stack trace
  • mailer_class - The mailer class name
  • mailer_action - The mailer action/method name
  • to, from, subject - Email metadata
  • attachment_count - Number of attachments
  • additional_data - Custom context (account_id, user_id, etc.)

Error Handling Flow

  1. Email delivery fails with an exception
  2. Rails rescue_from catches the exception
  3. LogStruct method is called (e.g., log_and_ignore_error)
  4. LogStruct creates structured error log
  5. Your notification subscriber receives the log
  6. You send custom notifications based on error type