Skip to content

Instantly share code, notes, and snippets.

@superherointj
Created June 4, 2020 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superherointj/359f2f88145490d1b198fad9d3be2d51 to your computer and use it in GitHub Desktop.
Save superherointj/359f2f88145490d1b198fad9d3be2d51 to your computer and use it in GitHub Desktop.
OCaml, LWT, Rresult - Catching exception before reaching Lwt_main.run
(executable
(name lwt_demo1)
(public_name lwt_demo1.exe)
(libraries rresult lwt lwt.unix)
(preprocess (pps lwt_ppx))
(flags (:standard -warn-error -22))
)
Fatal error: exception Unix.Unix_error(Unix.ENOENT, "open", "a_non_existent_filename")
Raised by primitive operation at file "src/unix/lwt_unix.cppo.ml", line 235, characters 14-31
Re-raised at file "lwt_demo1.ml", line 28, characters 4-233
Re-raised at file "src/core/lwt.ml", line 3027, characters 20-29
Called from file "src/unix/lwt_main.ml", line 27, characters 10-20
Called from file "src/unix/lwt_main.ml", line 114, characters 8-13
Re-raised at file "src/unix/lwt_main.ml", line 120, characters 4-13
Called from file "lwt_demo1.ml", line 38, characters 9-33
(*
I want to catch an exception before it reaches Lwt_main.run.
I know I can catch the exception at Lwt_main. Just want to avoid it somehow.
*)
open Rresult
let printLine line =
let newline = "-> " ^ line in
let () = print_endline newline in
newline
;;
let resultOpenFile =
try%lwt
Lwt.return (R.ok (Lwt_io.open_file ~mode:Input "a_non_existent_filename"))
with
| Unix.Unix_error (uerr, ucommand, dir) ->
(match uerr with
| ENOENT -> Lwt.return (R.error ("NEVER CALLED - ENOENT"))
| _ -> Lwt.return (R.error "NEVER CALLED"))
| _ -> Lwt.return (R.error "NEVER CALLED")
;;
let mainPromise =
match%lwt resultOpenFile with
| Ok wrappedInputChannel ->
(* If Ok, Let's print result *)
let%lwt inputChannel = wrappedInputChannel in
let strLwtStream = Lwt_io.read_lines inputChannel in
let%lwt resultList = Lwt_stream.to_list strLwtStream in
let _list = List.map printLine resultList in
Lwt.return ()
| Error _ ->
let () = print_endline "RRESULT Some error happened" in
Lwt.return ()
;;
let () = Lwt_main.run mainPromise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment