Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

How to handle the fact that js and js libs are throwing exceptions all over?

$
0
0

Here’s an example function to wrap an external function that might throw an error.

let tryCatch = fn => {
  try {
    let t = fn()
    Some(t)
  } catch {
  | _ => None
  }
}

@module("./foo.mjs")
external fn: unit => int = "fn"

Console.log(tryCatch(fn))
// foo.mjs
export let fn = () => {
    throw new Error('Error');
}

This will never throw and just returns None.

You can also do something similar with a result type if you want to keep track of the error.

You don’t need to do this everywhere, just at a few key points in the program where you don’t want to throw an exception.


Viewing all articles
Browse latest Browse all 2592

Trending Articles