transitions icon indicating copy to clipboard operation
transitions copied to clipboard

prepare func raises Exception altough on_exception is defined

Open match1 opened this issue 2 years ago • 0 comments

Describe the bug When using a _can_trigger: If a prepare callback raises an Exception, this exception gets propangated to the calling code even if you define an on_exception callback.

Minimal working example

from transitions.core import Machine


class Amp:
    def __init__(self):
        self._external_resource: None | str = None
        self.machine = Machine(
            self,
            send_event=True,
            states=[
                "silent",
                "loud",
            ],
            transitions=[
                {
                    "trigger": "turn_up",
                    "source": "silent",
                    "dest": "loud",
                    "prepare": "fetch_external_resource",
                    # "conditions": "is_external_resource_ready",
                },
            ],
            initial="silent",
            on_exception="on_exception",
        )


    def fetch_external_resource(self, event):
        print("Refresh something..")
        self._external_resource = "something"
        # but this can fail
        raise ValueError("Something went wrong")
    
    def on_exception(self, event):
        print(f"Handling exception correctly {event.error=!r}")

amp = Amp()
amp.turn_up()
print (f"State is still {amp.state}")
try:
    amp.may_turn_up()
except ValueError:
    print("An exception got raised altough we defined on_exception")


Expected behavior The on_exception callback gets called when you use may_turn_up()? At least thats what I would expect.

match1 avatar Aug 09 '23 15:08 match1