Skip to content

Commit ce34434

Browse files
committed
Add Util.tag_exn_with
Add the utilitary function tag_exn_with to run a function while wrapping all uncaught exceptions into an internal exception that will track what was run and not only the uncaught exception This will allow STM and Lin to run commands that should not raise exceptions and, in case they do raise an exception, display the faulty command along with the exception
1 parent 9f3c6b1 commit ce34434

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/util.ml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,25 @@ let protect (f : 'a -> 'b) (a : 'a) : ('b, exn) result =
7575
try Result.Ok (f a)
7676
with e -> Result.Error e
7777

78+
exception Uncaught_exception of string * exn
79+
80+
let print_uncaught_exception e =
81+
match e with
82+
| Uncaught_exception (cmd, exc) ->
83+
Some
84+
(Format.sprintf "%s raised but not caught while running %s"
85+
(Printexc.to_string exc) cmd)
86+
| _ -> None
87+
88+
let _ =
89+
Printexc.register_printer print_uncaught_exception
90+
91+
let tag_exn_with show run x =
92+
try run x
93+
with e ->
94+
let bt = Printexc.get_raw_backtrace () in
95+
Printexc.raise_with_backtrace (Uncaught_exception (show x, e)) bt
96+
7897
module Pp = struct
7998
open Format
8099

lib/util.mli

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ val print_triple_vertical :
4141
val protect : ('a -> 'b) -> 'a -> ('b, exn) result
4242
(** [protect f] turns an [exception] throwing function into a [result] returning function. *)
4343

44+
val tag_exn_with : ('a -> string) -> ('a -> 'b) -> 'a -> 'b
45+
(** [tag_exn_with show run x] behaves as [run x] unless raises an
46+
uncaught exception in which case it will wrap that exception along
47+
with [show x] into an internal exception. That exception will be
48+
printed as: ["... raised but not caught while running " ^ show x]. *)
49+
4450
module Pp : sig
4551
(** Pretty-printing combinators that generate valid OCaml syntax for common
4652
types along with combinators for user-defined types *)

0 commit comments

Comments
 (0)