Skip to content

Commit e81e334

Browse files
authored
Fix exception section in manual (rescript-lang#1958)
1 parent 53fe7bd commit e81e334

File tree

1 file changed

+17
-41
lines changed

1 file changed

+17
-41
lines changed

site/docsource/Exception-handling.adoc

+17-41
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,32 @@
11
## Exception handling between OCaml and JS (@since 1.7.0)
22

3-
In JS world, exception could be any data, while OCaml exception is structured data format and supports pattern match, catch OCaml exception on JS side is no-op.
3+
In the JS world, exception could be any data, while an OCaml exception is a structured data format and supports pattern matching. Catching an OCaml exception on JS side is therefore a no-op.
44

5-
### Catch JS exception
6-
7-
To catch Js exception on OCaml side, we categorize all JS exceptions to belong to `Js.Exn.Error`.
5+
JS exceptions can be raised from OCaml by using the `JS.Exn.raise*` functions, and can be caught as an OCaml exception of the type `Js.Exn.Error` with the JS exception as it's paylaod typed as `Js.Exn.t`. The JS Exception can then either be manipulated with the accessor functions in `Js.Exn`, or casted to a more appropriate type.
86

97
[source,ocaml]
108
--------------
11-
let example1 () =
12-
match Js.Json.exnParse {| {"x" }|} with
13-
| exception Js.Exn.Error err ->
14-
Js.log @@ Js.Exn.stack err;
15-
None
16-
| v -> Some v
17-
18-
let example2 () =
19-
try Some (Js.Json.exnParse {| {"x"}|}) with
20-
Js.Exn.Error _ -> None
21-
--------------
22-
23-
The exception definition of `Js.Exn.Error` is as below:
24-
25-
[source,ocaml]
26-
--------------
27-
type t =
28-
< stack : string Js.undefined ;
29-
message : string Js.undefined ;
30-
name : string Js.undefined;
31-
fileName : string Js.undefined
32-
> Js.t
33-
34-
exception Error of t
9+
let () =
10+
try
11+
Js.Exn.raiseError "oops!"
12+
with
13+
| Js.Exn.Error e ->
14+
match Js.Exn.message e with
15+
| Some message -> Js.log {j|Error: $message|j}
16+
| None -> Js.log "An unknown error occurred"
3517
--------------
3618

37-
### Raise JS style exception
38-
39-
We provide such functions
40-
4119
[source,ocaml]
4220
--------------
43-
(** Raise Js exception Error object with stacktrace *)
44-
val error : string -> 'a
45-
val evalError : string -> 'a
46-
val rangeError : string -> 'a
47-
val referenceError : string -> 'a
48-
val syntaxError : string -> 'a
49-
val typeError : string -> 'a
50-
val uriError : string -> 'a
21+
let maybeParsed =
22+
match Js.Json.parseExn {| {"x" }|} with
23+
| value -> Some value
24+
| exception Js.Exn.Error e ->
25+
Js.log (Js.Exn.message e);
26+
None
5127
--------------
5228

53-
Please consult module link:../api/Js.Exn.html[`Js.Exn`] for more details
29+
Please consult the link:../api/Js.Exn.html[`Js.Exn` API reference] for more details
5430

5531

5632
## `bs.open`: Type safe external data-source handling (@@since 1.7.0)

0 commit comments

Comments
 (0)