| 1 | /** |
| 2 | * @title Using Effect.gen |
| 3 | * |
| 4 | * Use `Effect.gen` to write code in an imperative style similar to async await. |
| 5 | * You can use `yield*` to access the result of an effect. |
| 6 | */ |
| 7 | |
| 8 | import { Effect, Schema } from "effect" |
| 9 | |
| 10 | Effect.gen(function*() { |
| 11 | yield* Effect.log("Starting the file processing...") |
| 12 | yield* Effect.log("Reading file...") |
| 13 | |
| 14 | // Always return when raising an error, to ensure typescript understands that |
| 15 | // the function will not continue executing. |
| 16 | return yield* new FileProcessingError({ message: "Failed to read the file" }) |
| 17 | }).pipe( |
| 18 | // Add additional functionality with .pipe |
| 19 | Effect.catch((error) => Effect.logError(`An error occurred: ${error}`)), |
| 20 | Effect.withSpan("fileProcessing", { |
| 21 | attributes: { |
| 22 | method: "Effect.gen" |
| 23 | } |
| 24 | }) |
| 25 | ) |
| 26 | |
| 27 | // Use Schema.TaggedError to define a custom error |
| 28 | export class FileProcessingError extends Schema.TaggedError<FileProcessingError>()("FileProcessingError", { |
| 29 | message: Schema.String |
| 30 | }) {} |