repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / docs / posts
Eric Bower · 26 Aug 24

error-handling.md

 1---
 2title: Error handling
 3description: How to manage errors
 4---
 5
 6By leveraging `effection` and [structured concurrency](/structured-concurrency)
 7we can let it do most of the heavy lifting for managing errors.
 8
 9> Read [error handling](https://frontside.com/effection/docs/errors) doc at
10> `effection`!
11
12There are some tools `starfx` provides to make it a little easier.
13
14By default in `effection`, if a child task raises an exception, it will bubble
15up the ancestry and eventually try to kill the root task. Within `starfx`, we
16prevent that from happening with [supervisor](/supervisors) tasks. Having said
17that, child tasks can also control how children tasks are managed. Sometimes you
18want to kill the child task tree, sometimes you want to recover and restart, and
19sometimes you want to bubble the error up the task ancestry.
20
21If you want to capture a task and prevent it from bubbling an exception up, then
22you have two `fx`: `call` and `safe`.
23
24```ts
25import { call, run, safe } from "starfx";
26
27function* main() {
28  try {
29    // use `call` to enable JS try/catch
30    yield* call(fetch("api.com"));
31  } catch (err) {
32    console.error(err);
33  }
34
35  // -or- if you don't want to use try/catch
36  const result = yield* safe(fetch("api.com"));
37  if (!result.ok) {
38    console.error(result.err);
39  }
40}
41
42await run(main);
43```
44
45Both functions will catch the child task and prevent it from bubbling up the
46error.