Throwing javascript errors from js_of_ocaml

How can I throw a javascript error from OCaml code using js_of_ocaml, in such a way that the message string will be available when the error is caught by javascript? I’ve tried

let error = Js.Unsafe.global##.Error in
let js_error = new%js error (Js.string msg) in
Js_error.raise_ (Js_error.of_error js_error)

and also

Js_error.raise_
  (Js_error.of_error
     (object%js
        val mutable name = Js.string "name"
        val mutable message = Js.string msg
        val mutable stack = Js.undefined
        method toString = Js.string "toString"
     end))

but in both cases my javascript code

try {
  // call OCaml
} catch(err) {
  console.log(err.message);
}

shows “undefined”.

The two things you’ve tried should work.
I think you’re not giving enough information in your description. There must be some ocaml code catching the js exception and reraising it. When ocaml code catches a js error, it will wrap it so that it looks like an ocaml exception. You should be able to fix this if you put your ocaml code inside a

try
  <BODY>
with
| Js_of_ocaml.Js.Js_error.Exn e -> 
  Js_of_ocaml.Js.Js_error.raise_ e

I want to catch the error from javascript, not from OCaml. I included the javascript code I’m using to catch the error. I showed the OCaml code I’m using that calls Js_error.raise_.

I understood your question correctly. What I am saying is that to explain the behavior you are seeing, there must be some other OCaml code involved (that re-raises a caught exception). There are details missing in your descriptions. For examples, where does the javascript code get the ocaml function from ? Is the ocaml function exported to the global object ? if yes, how ?

It would be easier to help if you could provide full instruction to reproduce the issue.

1 Like