'backtrace' on OCaml errors

Is there a ppx / some macro trick for handling the following:

I want something where

input:
  EXPR : some OCaml expr
  msg: String


output:
try EXPR with
  err -> failwith(Printf.sprintf "%s\n%s\n" err msg)

The point is: I want to provide extra information on an exception, a “fake manual stacktrace” of sorts.

I don’t need exactly the above; just the gist of the above.

Why not use functions?

let catch (f : unit -> 'a) (msg : string) : 'a =
  try
    f ()
  with exn ->
    failwith (Printf.sprintf "%s\n%s\n" (Printexc.to_string exn) msg) 

Cheers,
Nicolas

1 Like

I believe (1) this involves wrapping everything in thunks and (2) macros can get rid of the thunk problem. Thus, the suggestion for macro; however, I am not 100% sure.