views:

102

answers:

1

Is there a nice way to tell AASM that if an exception is raised while processing any assm_event I want that error to be caught by a specific block of code?

eg currently I do something like

assm_state :state_1
assm_state :state_2, :before_enter => :validate_something
assm_state :failed


assm_event :something_risky do
  transition :from => :state_1, :to => :state_2
end

assm_event :fail do
  transition :from => [:state_1, :state_2], :to => :failed
end

def validate_something
  begin
    something_that_might_raise_error
  rescue
    self.record_error
    self.fail
  end
end

and what I would prefer to do is something like

assm_state :state_1
assm_state :state_2, :before_enter => :validate_something
assm_state :failed


assm_event :something_risky, :on_exception => :log_failure do
  transition :from => :state_1, :to => :state_2
end

assm_event :fail do
  transition :from => [:state_1, :state_2], :to => :failed
end

def validate_something
    something_that_might_raise_exception
end

def log_failure
  self.record_error
  self.fail
end

and have log_failure be called if something_that_might_raise_exception does raise an exception. Ideally I want to avoid changing AASM so I am safe if I need to upgrade it in the future

A: 

If you use SimpleStateMachine you can do:

  def something_risky
    something_that_might_raise_error
  rescue
    record_error
    raise #reraise the error
  end
  event :something_risky, :state1 => :state2,
                          RuntimeError => :failed