| title | Wrapping Synchronous and Asynchronous Computations | |||||||
|---|---|---|---|---|---|---|---|---|
| id | constructor-try-trypromise | |||||||
| skillLevel | beginner | |||||||
| applicationPatternId | core-concepts | |||||||
| summary | Use try and tryPromise to safely wrap synchronous or asynchronous computations that may throw or reject, capturing errors in the Effect world. | |||||||
| tags |
|
|||||||
| rule |
|
|||||||
| related |
|
|||||||
| author | PaulJPhilp | |||||||
| lessonOrder | 28 |
Use the try and tryPromise constructors to safely wrap synchronous or asynchronous computations that may throw exceptions or reject promises.
This captures errors in the Effect failure channel, making them type-safe and composable.
Wrapping potentially unsafe code in try or tryPromise ensures that all errors are handled in a uniform, declarative way.
This eliminates the need for try/catch blocks and makes error handling explicit and type-safe.
import { Effect } from "effect";
// Synchronous: Wrap code that may throw
const effectSync = Effect.try({
try: () => JSON.parse("{ invalid json }"),
catch: (error) => `Parse error: ${String(error)}`,
}); // Effect<string, never, never>
// Asynchronous: Wrap a promise that may reject
const effectAsync = Effect.tryPromise({
try: () => fetch("https://api.example.com/data").then((res) => res.json()),
catch: (error) => `Network error: ${String(error)}`,
}); // Effect<string, any, never>Explanation:
Effect.trywraps a synchronous computation that may throw, capturing the error in the failure channel.Effect.tryPromisewraps an async computation (Promise) that may reject, capturing the rejection as a failure.
Using try/catch for error handling, or relying on untyped Promise rejections, which leads to less composable and less type-safe code.