BuckleScript

BuckleScript

  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Interop

Intro

  • What & Why
  • Installation
  • New Project
  • Try
  • Concepts Overview
  • Upgrade Guide to v7

Interop

  • Overview
  • Cheatsheet
  • Embed Raw JavaScript
  • Common Data Types
  • Intro to External
  • Bind to Global Values
  • Null, Undefined & Option
  • Object
  • Object 2
  • Class
  • Function
  • Property access
  • Return value wrapping
  • Import & Export
  • Regular Expression
  • Exceptions
  • JSON
  • Pipe First
  • Generate Converters & Helpers
  • Better Data Structures Printing (Debug Mode)
  • NodeJS Special Variables
  • Miscellaneous
  • Browser Support & Polyfills

Build System

  • Overview
  • Configuration
  • Automatic Interface Generation
  • Interop with Other Build System
  • Performance
  • Advanced

Standard Library

  • Overview

Advanced

  • Conditional Compilation
  • Extended Compiler Options
  • Use Existing OCaml Libraries
  • Difference from Native OCaml
  • Compiler Architecture & Principles
  • Comparison to Js_of_ocaml
Edit

Exceptions

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 therefore doesn't work as intended.

JS exceptions can be raised from the BuckleScript side by using the JS.Exn.raise* functions, and can be caught as a BS exception of the type Js.Exn.Error with the JS exception as its payload, 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.

try
  Js.Exn.raiseError "oops!"
with
| Js.Exn.Error e ->
  match Js.Exn.message e with
  | Some message -> Js.log {j|Error: $message|j}
  | None -> Js.log "An unknown error occurred"
try (
  Js.Exn.raiseError("oops!")
) {
| Js.Exn.Error(e) =>
  switch (Js.Exn.message(e)) {
  | Some(message) => Js.log({j|Error: $message|j})
  | None => Js.log("An unknown error occurred")
  }
};

Usage

Take promise for example:

exception UnhandledPromise

let handlePromiseFailure = function [@bs.open]
  | Not_found ->
    Js.log "Not found";
    Js.Promise.resolve ()

let _ =
 Js.Promise.reject Not_found
 |> Js.Promise.catch (fun error ->
      match handlePromiseFailure error with
      | Some x -> x
      | None -> raise UnhandledPromise
  )
exception UnhandledPromise;

let handlePromiseFailure =
  [@bs.open]
  (
    fun
    | Not_found => {
        Js.log("Not found");
        Js.Promise.resolve()
      }
  );

Js.Promise.reject(Not_found)
  |> Js.Promise.catch(
     (error) =>
       switch (handlePromiseFailure(error)) {
       | Some(x) => x
       | None => raise(UnhandledPromise)
       }
   );
Last updated on 4/13/2020
← Regular ExpressionJSON →
  • Usage