Skip to content

Commit 156f82c

Browse files
committed
Add Js_exn.unsafeAnyToExn function
1 parent d04e07c commit 156f82c

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-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 unsafeAnyToExn 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: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,25 @@ external isCamlExceptionOrOpenVariant:
4343
'a -> bool = "caml_is_extension"
4444
(** internal use only *)
4545

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

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

0 commit comments

Comments
 (0)