Catching All Errors

Avatar of Hemanta SundarayHemanta Sundaray

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:

http.ts
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 user
Effect.runPromise(fetchUser(1)).then(
(user) => console.log("User:", user.firstName, user.lastName),
(error) => console.error(`[${error._tag}] ${error.message}`),
);
// Test with an invalid user
Effect.runPromise(fetchUser(9999)).then(
(user) => console.log("User:", user.firstName, user.lastName),
(error) => console.error(`[${error._tag}] ${error.message}`),
);

Output:

Terminal
[UserFetchError] Failed to fetch user 9999
User: Emily Johnson

HttpClient.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.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.