typelevel / typelevel/cats

Add bridge from Throwable to E for ApplicativeError

Open
#4,286 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Scala
Stars
5.5k
Forks
1.2k
Avg merge
2d 10h
Merged PRs (30d)
5

Description

Interacting with code that can throw exceptions can be awkward when working with ApplicativeError if E isn't Throwable, because the ApplicativeError#catch* methods don't really have a way to bridge into F unless you know what F is.

You can absolutely make it work, you just can't really leverage the ApplicativeError#catch* helpers, which is a shame because they're really handy, and I think it would be really straightforward to offer alternatives that are more generally applicable.

I propose adding parallel methods which would allow adapting a Throwable to an E. For example, ApplicativeError#catchNonFatalAs could look like this:

  /**
   * Often E can be created from Throwable. Here we try to call pure or 
   * catch, adapt into E, and raise.
   *
   * Exceptions that cannot be adapted to E will be propagated 
   */
  def catchNonFatalAs[A](adaptIfPossible: Throwable => Option[E])(a: => A): F[A] =
    try pure(a)
    catch {
      case NonFatal(e) => adaptIfPossible(e).map(raise(_)).getOrElse(throw e)
    }

Similar methods could be created for ApplicativeError#catchNonFatalEval and ApplicativeError#catchOnly.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the ApplicativeError definition and its existing catch* methods. Compare the proposed catchNonFatalAs, catchNonFatalEval, and catchOnly variants, then add coverage showing Throwable adaptation into E and propagation when adaptation fails; done means the parallel helpers are available with consistent behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.