Trailblazer: Which step caused my operation to fail?

625 views Asked by At

Given an operation like

class MyOperation < Trailblazer::Operation
  step :do_a!
  step :do_b!

  def do_a(options, **)
    false
  end

  def do_b(options, **)
    true
  end
end

and the result of run(MyOperation), how can I tell which step of the operation failed?

If the result object doesn't contain this info by default, what's a good way to add it?

2

There are 2 answers

2
Yogesh Khater On

There is this gem now which provides operation specific debugging utilities - https://github.com/trailblazer/trailblazer-developer

It allows you to see exactly which step raised the exception or which step caused the track to change from success to failure.

Trailblazer::Developer.wtf?(MyOperation, options)

It will print the trace of steps on STDOUT/Logger.

enter image description here

0
Ibrahim Areda On

Besides the trailblazer-developer gem, I would like to point out that you can handle failing steps with failure methods.

In your controller use the helper run provided by Trailblazer that allows you to call an operation and inject the result (result object of the operation) in the controller, then you can access all of the context properties.

 # my_operation.rb
 class MyOperation < Trailblazer::Operation
   step :do_a
   failure :fail_a
    
   def fail_a(context, **)
     context[:error] = 'Step A failed.'
   end
  end

  # my_controller.rb
  class MyController < ApplicationController
    def do_a
      run MyOperation do
        return render json: { success: true }, status: :ok
      end

      render json: {
        success: false,
        error: result[:error]
      }, status: :unprocessable_entity
    end
  end