Skip to content

Latest commit

 

History

History
66 lines (53 loc) · 2.1 KB

File metadata and controls

66 lines (53 loc) · 2.1 KB
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
try
tryPromise
constructor
effect
error
async
interop
rule
description
Use try and tryPromise to lift code that may throw or reject into Effect, capturing errors in the failure channel.
related
constructor-succeed-some-right
constructor-fail-none-left
constructor-sync-async
author PaulJPhilp
lessonOrder 28

Wrapping Synchronous and Asynchronous Computations

Guideline

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.

Rationale

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.

Good Example

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.try wraps a synchronous computation that may throw, capturing the error in the failure channel.
  • Effect.tryPromise wraps an async computation (Promise) that may reject, capturing the rejection as a failure.

Anti-Pattern

Using try/catch for error handling, or relying on untyped Promise rejections, which leads to less composable and less type-safe code.