Error Handling - messagebus/lapine GitHub Wiki

Consumer Handlers

When dispatching messages to handlers, errors may occur for various reasons. At the moment, error handling is extremely simple.

  • All errors are caught
  • Errors are run through a configurable error handler

All errors are caught

This means that error states can be extremely confusing. One might expect that errors would halt execution and keep the message from being ack'd to RabbitMQ. That is currently not the case.

Errors are run through a configurable error handler

The default error handler just logs messages to $stderr. A custom error handler allows for different behavior. An error handler just needs to respond to call, with the arguments error, data and metadata.

If the dispatcher raises an error while unpacking the JSON payload, then data will be the raw payload as a string. If the dispatcher raises any other error, then the unpacked payload will be sent to the error handler.


if defined?(Lapine::Consumer::Dispatcher)
  lapine_error_log = Logger.new('/var/log/my-app/lapine.stderr.log')

  Lapine::Consumer::Dispatcher.error_handler = ->(e, data, metadata) {
    metadata_hash = metadata.to_hash

    lapine_error_log.error "[#{Time.now.utc}] [#{metadata.routing_key}] " \
      "Lapine error: #{e.class.name}: #{e.message}\n" \
      "  payload: #{data}\n" \
      "  metadata: #{metadata_hash}\n" \
      "    #{e.backtrace.join("\n    ")}"

    NewRelic::Agent.notice_error(e,
      payload: data, 
      metadata: metadata_hash,
      routing_key: metadata.routing_key)
  }
end