Skip to content

Commit 226bfcf

Browse files
authored
Merge pull request #4905 from ryyppy/js-exn-experiments
Add Js_exn.anyToExnInternal function
2 parents 40bfbc0 + b9c7a7d commit 226bfcf

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

jscomp/others/js_exn.ml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ external makeError : string -> error = "Error" [@@bs.new]
4545
external isCamlExceptionOrOpenVariant :
4646
'a -> bool = "caml_is_extension"
4747

48+
let anyToExnInternal obj =
49+
if isCamlExceptionOrOpenVariant obj then
50+
(Obj.magic obj : exn)
51+
else
52+
Error ((Obj.magic obj) : t)
53+
4854
let raiseError str =
4955
raise (Obj.magic (makeError str : error) : exn)
5056

jscomp/others/js_exn.mli

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,28 @@ external isCamlExceptionOrOpenVariant:
4343
'a -> bool = "caml_is_extension"
4444
(** internal use only *)
4545

46+
val anyToExnInternal: 'a -> exn
47+
(**
48+
* [anyToExnInternal obj] will take any value [obj] and wrap it
49+
* in a Js.Exn.Error if given value is not an exn already. If
50+
* [obj] is an exn, it will return [obj] without any changes.
51+
*
52+
* This function is mostly useful for cases where you want to unify a type of a value
53+
* that potentially is either exn, a JS error, or any other JS value really (e.g. for
54+
* a value passed to a Promise.catch callback)
55+
*
56+
* IMPORTANT: This is an internal API and may be changed / removed any time in the future.
57+
*
58+
* @example {[
59+
* switch (Js.Exn.unsafeAnyToExn("test")) {
60+
* | Js.Exn.Error(v) =>
61+
* switch(Js.Exn.message(v)) {
62+
* | Some(str) => Js.log("We won't end up here")
63+
| None => Js.log2("We will land here: ", v)
64+
* }
65+
* }
66+
* ]}
67+
* **)
4668

4769
(** Raise Js exception Error object with stacktrace *)
4870
val raiseError : string -> 'a

0 commit comments

Comments
 (0)