Handling errors in the Effect library can be a bit tricky at first, especially when dealing with ...

👋 Hello! I am very new to effect and am trying to figure out how to handle errors between my services.

I have 2 services, when one throws an error I cannot seem to handle it.

Here is a mock implementation of my DatabaseService

const DatabaseServiceMock = Layer.effect(
  DatabaseService,
  Effect.sync(() => {
    return {
      upsert: () =>
        pipe(
          Effect.promise(async () => {
            return Effect.fail(
              new DatabaseUpsertError('bad thing happened')
            );
          }),
          Effect.flatten,
        ),
      query: () =>
        Effect.promise(async () => {
          return {
            data: [],
            error: 'bad thing happened',
          } as PostgrestSingleResponse<any>;
        }),
    };
  }),
);


I have tried various ways of trying to handle this error. I still have some confusion around how to "unwrap" the effect responses. In my other service I just want to be able to handle the error and return an appropriate response

  const result = yield* pipe(
    Effect.match(
      Effect.promise(async () =>
        database.upsert('TableName', upsertList),
      ),
      {
        onFailure: (error) => {
          console.log('ERROR', error);
          return { error: 1 };
        },
        onSuccess: (res) => {
          console.log('SUCCESS', res);
          return res;
        },
      },
    ),
    Effect.flatten,
  );


When I run the code with the mocked out service I end up seeing the code hit the success path, yet still reporting an error.

Any help is appreciated
Was this page helpful?