Skip to main content

Context & User

Adding context to errors helps you debug faster by understanding exactly what was happening when an error occurred.

User Context

Identify which user experienced the error:
BrainzLab.set_user(
  id: current_user.id,
  email: current_user.email,
  name: current_user.name
)

In Rails

Set user context in a before_action:
class ApplicationController < ActionController::Base
  before_action :set_brainzlab_user

  private

  def set_brainzlab_user
    return unless current_user

    BrainzLab.set_user(
      id: current_user.id,
      email: current_user.email,
      name: current_user.name,
      plan: current_user.plan,
      organization_id: current_user.organization_id
    )
  end
end

Custom User Fields

Add any fields relevant to your app:
BrainzLab.set_user(
  id: user.id,
  email: user.email,
  name: user.name,
  # Custom fields
  plan: user.subscription.plan,
  role: user.role,
  company: user.company.name,
  signup_date: user.created_at.iso8601
)

Tags

Tags are indexed for fast searching:
BrainzLab.set_tags(
  feature: "checkout",
  environment: "production",
  version: "2.3.1"
)
Search by tags in the dashboard:
tag.feature:checkout
tag.version:2.3.1

Extra Context

Add arbitrary data to the error:
BrainzLab::Reflex.capture(exception,
  extra: {
    order_id: order.id,
    cart_items: cart.items.map(&:id),
    payment_method: order.payment_method,
    attempted_at: Time.current.iso8601
  }
)

Request Context

Automatically captured in Rails:
  • URL - Full request URL
  • Method - GET, POST, etc.
  • Headers - Request headers (sensitive ones filtered)
  • Params - Request parameters (sensitive ones filtered)
  • Session - Session data

Filtering Sensitive Data

Configure which fields to scrub:
BrainzLab.configure do |config|
  config.scrub_fields = [
    :password,
    :password_confirmation,
    :credit_card,
    :cvv,
    :ssn,
    /token/i,
    /secret/i
  ]
end

Environment Context

Automatically captured:
  • Ruby version
  • Rails version
  • Gem versions
  • Hostname
  • Process ID
  • Git commit
  • Git branch

Block-Scoped Context

Add context for a specific operation:
BrainzLab.with_context(order_id: order.id, step: "payment") do
  process_payment(order)
  # Any errors here include order_id and step
end

Per-Error Context

Add context when capturing:
begin
  charge_card(order)
rescue Stripe::CardError => e
  BrainzLab::Reflex.capture(e,
    user: { id: user.id },
    tags: { provider: "stripe" },
    extra: {
      order_id: order.id,
      amount: order.total,
      card_type: order.card_type
    }
  )
end

Context Priority

When the same key exists in multiple places:
  1. Per-error context (highest priority)
  2. Block-scoped context
  3. Global context (lowest priority)
BrainzLab.set_context(source: "global")

BrainzLab.with_context(source: "block") do
  BrainzLab::Reflex.capture(e, extra: { source: "error" })
  # source = "error"
end