fp-ts: `either.tryCatch`: `onerror` param?

task.tryCatch has an onrejected param. This is useful because it allows you to define the type of the error:

export declare const tryCatch: <L, A>(f: Lazy<Promise<A>>, onrejected: (reason: {}) => L) => Task<Either<L, A>>;

However, either.tryCatch does not have this. Instead, it assumes the error type will be Error—but as we know, that’s not always the case in JS!

Would you accept a PR to add an onerror param to either.tryCatch?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (3 by maintainers)

Commits related to this issue

Most upvoted comments

What about

const toError = (e: {}): Error => {
  if (e instanceof Error) {
    return e
  } else {
    return new Error(String(e))
  }
}

/** @function */
export const tryCatch = <A>(f: Lazy<A>, onerror: (e: {}) => Error = toError): Either<Error, A> => {
  try {
    return right(f())
  } catch (e) {
    return left(onerror(e))
  }
}

This is backward compatible, has a handy default (for interop with sane libraries), solves the existing bug and allows for custom refinements