How to return error from `taskEither.tryCatch`

29 Views Asked by At

I have the following probem:

const something = taskEither.tryCatch(
  async()  => {
    const random = Math.random();
    if (random < 0.5) throw new Error();
    return random < 0.25;
  },
  () => 'innerError' as const,
);
taskEither.tryCatch(
  async() => {
    const result = await something();
    if (either.isLeft(result)) return result.left;
    if (!result.right) throw new Error();
    return result.right;
  },
  () => 'OuterError' as const,
)

The type I want is TaskEither<'OuterError' | 'InnerError', true> but I get TaskEither<'OuterError', 'InnerError' | true>.

How can I get the Error in the left side to the Error in the right side?

1

There are 1 best solutions below

1
Florat On

I found a solution for my problem. But I wonder if there is a more idiomatic way to handle this because err is typed as unknown and forces to manually annotate the type. This can be problematic when there are many different errors thrown by the inner function.

taskEither.tryCatch(
  async() => {
    const result = await something();
    if (either.isLeft(result)) throw(result.left);
    if (!result.right) throw new Error();
    return result.right;
  },
  (err) => {
    if (err === 'InnerError') return <'InnerError'>'InnerError';
    return 'OuterError' as const;
  }
)