Skip to main content

StateEvents

Lifecycle hooks optionally overridden on state classes.

Default implementations on TopState are empty for entry/exit and rethrow for errors. Only states that define their own onEntry/onExit participate in verbose trace exit lists.

Type Parameters

Context

Context

Protocol

Protocol extends { } | undefined

Methods

onExit()

onExit(): void | Promise<void>

Invoked when leaving this state during an external transition.

Runs during the exit phase after the triggering handler completes and before the prototype switches away. Async onExit is awaited before continuing up the LCA path.

Returns

void | Promise<void>

Throws

TransitionError when this hook throws — may route to FatalErrorState

Remarks

Not called for internal transitions (handler returns without State.transition). Not called on Hsm.restore. Self-transitions may skip exit when optimized.


onEntry()

onEntry(): void | Promise<void>

Invoked when entering this state during initialization or an external transition.

Runs during the entry phase after the prototype points at this state. Async onEntry is awaited before entering nested initial substates or running deeper onEntry hooks.

Returns

void | Promise<void>

Throws

TransitionError or InitializationError when this hook throws

Remarks

During makeHsm(..., initialize: true), onEntry runs from root down through each @InitialState chain to the initial leaf. Schedule follow-up transitions via Base.post, not State.transition, from within onEntry.


onError()

onError<EventName>(error): void | Promise<void>

Recovery hook when an event handler throws EventHandlerError.

Type Parameters

EventName

EventName extends string | number | symbol

Correlated event key from Protocol

Parameters

error

RuntimeError<Context, Protocol, EventName>

Typed runtime error with RuntimeError.eventName, RuntimeError.eventPayload, HsmError.context, and HsmError.cause

Returns

void | Promise<void>

Throws

Rethrow to propagate; throwing here becomes FatalError

Remarks

Default TopState implementation rethrows. Override to log, transition to a safe state, or swallow. Uncaught errors invoke Properties.dispatchErrorCallback.


onUnhandled()

onUnhandled<EventName>(error): void | Promise<void>

Recovery hook when dispatch would raise UnhandledEventError.

Type Parameters

EventName

EventName extends string | number | symbol

Correlated event key from Protocol

Parameters

error

UnhandledEventError<Context, Protocol, EventName>

Describes the unmatched event and active state

Returns

void | Promise<void>

Throws

Default TopState implementation rethrows → may enter onError

Remarks

Override to implement catch-all handlers, auditing, or transition to an error state without defining every event on every leaf.