# Backtrace Handling in Monads

**URL:** <https://discuss.ocaml.org/t/backtrace-handling-in-monads/9419>\
**Category:** Learning\
**Created:** [February 26, 2022, 1:24am UTC](https://discuss.ocaml.org/t/backtrace-handling-in-monads/9419 "2022-02-26T01:24:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![totbwf](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/totbwf/32/3618_2.png) [@totbwf](https://discuss.ocaml.org/u/totbwf)\
**Post date:** [February 26, 2022, 1:24am UTC](https://discuss.ocaml.org/t/backtrace-handling-in-monads/9419/1 "2022-02-26T01:24:14Z")

</div>

I’m running into a bit of a tricky issue surrounding backtraces and monads, specifically a reader monad.  
Due to the inversion of control in `bind`, all the backtraces contain _only_ frames involving `bind`, which leads to some less than helpful traces:

```auto
        Raised at Core__Semantics.dispatch_rigid_hcom.go in file "src/core/Semantics.ml", line 1552, characters 6-67
        Called from Basis__Monad.MonadReaderResult.bind in file "src/basis/Monad.ml", line 169, characters 10-15
        Called from Basis__Monad.MonadReaderResult.bind in file "src/basis/Monad.ml", line 169, characters 10-15
... about 100 lines more of the same stuff

```

I know `lwt` has a clever trick involving a PPX + using the `reraise` primitive, but I was wondering if anyone else has any less invasive tricks that I could use to somehow massage these stack traces. Any help is appreciated!

For context, here’s the implementation of `bind`

```auto
  let bind m k env =
    match m env with
    | Ok a -> k a env
    | Error exn -> Error exn

```

---

<div class="post-metadata">

**Author:** ![yawaramin](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/yawaramin/32/3384_2.png) [@yawaramin](https://discuss.ocaml.org/u/yawaramin)\
**Post date:** [February 26, 2022, 3:35am UTC](https://discuss.ocaml.org/t/backtrace-handling-in-monads/9419/2 "2022-02-26T03:35:37Z")

</div>

As far as I know effect handlers are intended to be the OCaml answer to this. If this is experimental code it might be worth your while to port it to OCaml Multicore (or OCaml 5+trunk) and use effects.
