Skip to content

Commit 648723c

Browse files
Add exception handler to run_in_main_dont_wait
1 parent 4c0999e commit 648723c

File tree

3 files changed

+32
-7
lines changed

3 files changed

+32
-7
lines changed

src/unix/lwt_preemptive.ml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,9 @@ let run_in_main f =
258258
match CELL.get cell with
259259
| Result.Ok ret -> ret
260260
| Result.Error exn -> raise exn
261+
262+
(* This version shadows the one above, adding an exception handler *)
263+
let run_in_main_dont_wait f handler =
264+
let f () = Lwt.catch f (fun exc -> handler exc; Lwt.return_unit) in
265+
run_in_main_dont_wait f
266+

src/unix/lwt_preemptive.mli

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,13 @@ val run_in_main : (unit -> 'a Lwt.t) -> 'a
3434
retrieve values set this way inside [f ()], but not values set using
3535
{!Lwt.with_value} outside [f ()]. *)
3636

37-
val run_in_main_dont_wait : (unit -> unit Lwt.t) -> unit
38-
(** [run_in_main_dont_wait f] does the same as [run_in_main f] but a bit faster
37+
val run_in_main_dont_wait : (unit -> unit Lwt.t) -> (exn -> unit) -> unit
38+
(** [run_in_main_dont_wait f h] does the same as [run_in_main f] but a bit faster
3939
and lighter as it does not wait for the result of [f].
4040
41+
If [f]'s promise is rejected (or if it raises), then the function [h] is
42+
called with the rejection exception.
43+
4144
@since 5.7.0 *)
4245

4346
val init : int -> int -> (string -> unit) -> unit

test/unix/test_lwt_unix.ml

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,16 +1066,32 @@ let lwt_preemptive_tests = [
10661066
test "run_in_main_dont_wait" begin fun () ->
10671067
let p, r = Lwt.wait () in
10681068
let f () =
1069-
Lwt_preemptive.run_in_main_dont_wait (fun () ->
1070-
Lwt.pause () >>= fun () ->
1071-
Lwt.pause () >>= fun () ->
1072-
Lwt.wakeup r 42;
1073-
Lwt.return ())
1069+
Lwt_preemptive.run_in_main_dont_wait
1070+
(fun () ->
1071+
Lwt.pause () >>= fun () ->
1072+
Lwt.pause () >>= fun () ->
1073+
Lwt.wakeup r 42;
1074+
Lwt.return ())
1075+
(fun _ -> assert false)
10741076
in
10751077
Lwt_preemptive.detach f () >>= fun () ->
10761078
p >>= fun x ->
10771079
Lwt.return (x = 42)
10781080
end;
1081+
test "run_in_main_dont_wait_fail" begin fun () ->
1082+
let p, r = Lwt.wait () in
1083+
let f () =
1084+
Lwt_preemptive.run_in_main_dont_wait
1085+
(fun () ->
1086+
Lwt.pause () >>= fun () ->
1087+
Lwt.pause () >>= fun () ->
1088+
raise Exit)
1089+
(function Exit -> Lwt.wakeup r 45 | _ -> assert false)
1090+
in
1091+
Lwt_preemptive.detach f () >>= fun () ->
1092+
p >>= fun x ->
1093+
Lwt.return (x = 45)
1094+
end;
10791095
test "run_in_main_with_dont_wait" begin fun () ->
10801096
let p, r = Lwt.wait () in
10811097
let f () =

0 commit comments

Comments
 (0)