Skip to content

Commit a2408ba

Browse files
committed
Move exception handling docs to ApplicativeError
1 parent ef08cda commit a2408ba

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

docs/typeclasses/applicativemonaderror.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,42 @@ Running the following will result in `Right(0)`
176176
handlerErrorWith(attemptDivideApplicativeErrorAbove2(3, 0))
177177
```
178178

179+
### Handling Exceptions
180+
There will inevitably come a time when your nice `ApplicativeError` code will
181+
have to interact with exception-throwing code. Handling such situations is easy
182+
enough.
183+
184+
```scala mdoc
185+
def parseInt[F[_]](input: String)(implicit F: ApplicativeError[F, Throwable]): F[Int] =
186+
try {
187+
F.pure(input.toInt)
188+
} catch {
189+
case nfe: NumberFormatException => F.raiseError(nfe)
190+
}
191+
192+
parseInt[Either[Throwable, *]]("123")
193+
parseInt[Either[Throwable, *]]("abc")
194+
```
195+
196+
However, this can get tedious quickly. `ApplicativeError` has a `catchOnly`
197+
method that allows you to pass it a function, along with the type of exception
198+
you want to catch, and does the above for you.
199+
200+
```scala mdoc:nest
201+
def parseInt[F[_]](input: String)(implicit F: ApplicativeError[F, Throwable]): F[Int] =
202+
F.catchOnly[NumberFormatException](input.toInt)
203+
204+
parseInt[Either[Throwable, *]]("abc")
205+
```
206+
207+
If you want to catch all (non-fatal) throwables, you can use `catchNonFatal`.
208+
209+
```scala mdoc:nest
210+
def parseInt[F[_]](input: String)(implicit F: ApplicativeError[F, Throwable]): F[Int] = F.catchNonFatal(input.toInt)
211+
212+
parseInt[Either[Throwable, *]]("abc")
213+
```
214+
179215
## MonadError
180216

181217
### Description
@@ -190,7 +226,7 @@ The Definition for `MonadError` extends `Monad` which provides the
190226
methods, `flatMap`, `whileM_`. `MonadError` also provides error
191227
handling methods like `ensure`, `ensureOr`, `adaptError`, `rethrow`.
192228

193-
```
229+
```scala
194230
trait MonadError[F[_], E] extends ApplicativeError[F, E] with Monad[F] {
195231
def ensure[A](fa: F[A])(error: => E)(predicate: A => Boolean): F[A]
196232
def ensureOr[A](fa: F[A])(error: A => E)(predicate: A => Boolean): F[A]

0 commit comments

Comments
 (0)