Filtering for 2xx Status Only

Avatar of Hemanta SundarayHemanta Sundaray

If you want non-2xx status codes to be treated as errors, use filterStatusOk on the client:

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchUser(userId: number) {
return Effect.gen(function* () {
const client = (yield* HttpClient.HttpClient).pipe(
// All requests through this client will fail on non-2xx
HttpClient.filterStatusOk,
);
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("Found:", user.firstName),
(error) => console.error("Error:", error.message),
);
// Test with an invalid user
Effect.runPromise(fetchUser(9999)).then(
(user) => console.log("Found:", user.firstName),
(error) => console.error("Error:", error.message),
);

Output:

Terminal
Error: StatusCode: non 2xx status code (404 GET https://dummyjson.com/users/9999)
Found: Emily

When filterStatusOk rejects a response, it produces an HttpClientError with reason set to a StatusCodeError. The error includes both the original request and the response, so you have full context for debugging or recovery.

You can also use filterStatus for more control. It takes a predicate that receives the status code:

Terminal
// Only accept 200 and 201
HttpClient.filterStatus((status) => status === 200 || status === 201);

Sign in to save progress

Stay in the loop

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