Handling Errors
Error handling is critical for building robust workflows that can handle non-happy paths. It allows for short-circuiting operations and following an alternative path in the presence of expected but unusual situations. It can be seen as a more convenient alternative to Forks.
Errors defined and handled should be domain errors and not technical ones. Domain errors represent business-level exceptions that are meaningful in your workflow context, rather than implementation-specific exceptions like network failures or timeouts.
val doThings: WIO[MyState, MyError, Nothing] =
WIO.pure.error(MyError()).autoNamed()
val handleThatNastyError: WIO[(MyState, MyError), Nothing, MyState] =
WIO.pure(MyState(1)).autoNamed()
val errorHandled: WIO[MyState, Nothing, MyState] =
doThings.handleErrorWith(handleThatNastyError)
Rendering Outputs
- Flowchart
- BPMN
- Model
- Debug
{
"base" : {
"meta" : {
"name" : "Do Things",
"error" : {
"name" : "My Error"
},
"description" : null
},
"_type" : "Pure"
},
"handler" : {
"meta" : {
"name" : "Handle That Nasty Error",
"error" : null,
"description" : null
},
"_type" : "Pure"
},
"meta" : {
"newErrorMeta" : null,
"handledErrorMeta" : {
"name" : "My Error"
}
},
"_type" : "HandleError"
}
[HandleError](no-name)
- base: [Pure](Do Things)
Choosing the Handler at Runtime
The handler passed to handleErrorWith receives the state and the error as input, but its steps are fixed when the workflow is defined.
To choose the steps based on the state or the error, start the handler with WIO.pure and flatMap into the step you need.
flatMap only receives the state returned by the WIO.pure step, so copy anything the choice needs from the error into that state.
val incrementCounter: WIO[MyState, Nothing, MyState] = WIO.pure.makeFrom[MyState].value(s => s.copy(counter = s.counter + 1)).autoNamed()
val resetCounter: WIO[MyState, Nothing, MyState] = WIO.pure.makeFrom[MyState].value(_.copy(counter = 0)).autoNamed()
val chooseHandler: WIO[(MyState, MyError), Nothing, MyState] =
WIO.pure
.makeFrom[(MyState, MyError)]
.value((state, error) => state.copy(result = Some(error.toString)))
.autoNamed()
.flatMap(state => if state.counter < 3 then incrementCounter else resetCounter)
val errorHandledDynamically: WIO[MyState, Nothing, MyState] =
doThings.handleErrorWith(chooseHandler)
Until the handler runs, the step chosen inside flatMap is unknown, so visualizations show it as a dynamic step.
Drafting Support
For Error Handling, no dedicated draft API is required. Drafting can be done using the standard API.