pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.67k stars 529 forks source link

prepare func raises Exception altough on_exception is defined #626

Closed match1 closed 4 months ago

match1 commented 1 year ago

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.

aleneum commented 4 months ago

Hello @match1,

thank you very much for taking the time to report the bug report and creating the MWE. Much appreciated!