Skip to content

Add bridge from Throwable to E for ApplicativeError #4286

Open
@morgen-peschke

Description

@morgen-peschke

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions