Vibescript Showcase

Task error propagation

Catch a task error by wrapping Tasks.run in begin and rescue.

Showcase
Source showcase/concurrency/task_error_propagation.vibe
# title: Task error propagation
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Catch a task error by wrapping Tasks.run in begin and rescue.
# description: A task error appears when handle.value is read and again when the block exits. rescue turns that error into a regular return value.
# tags: concurrency, tasks, structured-concurrency, errors
# vibe: 0.4

def validate_amount(record)
  assert record[:amount] > 0, "amount must be positive"
  record[:amount]
end

def settle(record)
  begin
    Tasks.run do |tasks|
      handle = tasks.spawn(:validate_amount, record)
      amount = handle.value
      { id: record[:id], ok: true, amount: amount }
    end
  rescue
    { id: record[:id], ok: false, error: "validation failed" }
  end
end

def run
  {
    valid: settle({ id: "p1", amount: 50 }),
    invalid: settle({ id: "p2", amount: 0 })
  }
end
Output
Press Run example to run this code.