HttpClient.catch() intercepts every error from the client and lets you handle it. You can recover by returning an alternative response, or re-fail with a different error type.
In the example below, we catch all errors from the client and re-fail with a domain-specific UserFetchError:
import { FetchHttpClient, HttpClient, HttpClientRequest,} from "effect/unstable/http";import { Data, Effect } from "effect";
class UserFetchError extends Data.TaggedError("UserFetchError")<{ readonly userId: number;}> { get message() { return `Failed to fetch user ${this.userId}`; }}
function fetchUser(userId: number) { return Effect.gen(function* () { const client = (yield* HttpClient.HttpClient).pipe( HttpClient.filterStatusOk, HttpClient.catch((error) => { return Effect.fail(new UserFetchError({ userId })); }), );
const request = HttpClientRequest.get( `https://dummyjson.com/users/${userId}`, ); const response = yield* client.execute(request); const user = yield* response.json; return user; }).pipe(Effect.provide(FetchHttpClient.layer));}
// Test with a valid userEffect.runPromise(fetchUser(1)).then( (user) => console.log("User:", user.firstName, user.lastName), (error) => console.error(`[${error._tag}] ${error.message}`),);
// Test with an invalid userEffect.runPromise(fetchUser(9999)).then( (user) => console.log("User:", user.firstName, user.lastName), (error) => console.error(`[${error._tag}] ${error.message}`),);Output:
[UserFetchError] Failed to fetch user 9999User: Emily JohnsonHttpClient.catch transforms the client itself. Every request made through the resulting client will have this error handling applied. The callback receives the error and returns an Effect. You can recover by returning a replacement response, or re-fail with a different error type, as we do here by mapping HttpClientError to a domain-specific UserFetchError.