Effect CommunityEC
Effect Community12mo ago
2 replies
Karl

Creating a function to handle a specific error tag while maintaining type safety and flexibility ...

How can I create a function to handle a specific error tag?

I have several function that uses HttpClient from the @effect/platform package. When I use filterStatusOk, I don't get the error response in the error; the response content is hidden in the Effect named json. I tried to bring out the error content but I cannot create a function generic enough.

My attempt has been
function transformError(
            response: Effect.Effect<
                HttpClientResponse.HttpClientResponse,
                HttpClientError.ResponseError | HttpClientError.RequestError | HttpBodyError,
                Scope.Scope>) {
            return response.pipe(
                Effect.catchTag("ResponseError", Effect.fn(function* (error) {
                    const json = yield* error.response.json
                    return yield* new HttpClientError.ResponseError({
                        ...error,
                        cause: json
                    })
                }))
            )
        }


But some API calls do not have request body, and thus do not yield HttpBodyError, but this function makes every API function to have HttpBodyError.

This does not work
function transformError<E>(
            response: Effect.Effect<
                HttpClientResponse.HttpClientResponse,
                HttpClientError.ResponseError | E,
                Scope.Scope>) {
            return response.pipe(
                Effect.catchTag("ResponseError", Effect.fn(function* (error) {
                    const json = yield* error.response.json
                    return yield* new HttpClientError.ResponseError({
                        ...error,
                        cause: json
                    })
                }))
            )
        }

I think E needs to extend something that is compatible with yieldable Error (with _tag), although E can be nothing as well.
Was this page helpful?