Skip to content

Instantly share code, notes, and snippets.

@iHiD
Created September 7, 2016 21:42
Show Gist options
  • Save iHiD/dca38aacc5b1ca8ea19655685cb9129b to your computer and use it in GitHub Desktop.
Save iHiD/dca38aacc5b1ca8ea19655685cb9129b to your computer and use it in GitHub Desktop.
Ways around "x || exception" in JS
// Problem: This doesn't work
// true || throw new Error('some_var not defined')
// > Uncaught SyntaxError: Unexpected token throw
// I would approach this by creating another function, either for
// after the ||, or to wrap the whole thing. It's not exactly ideal
// but it feels idiomatic in a functional language.
//--
// Suggestion 1: Define a wrapper function for throw
//--
// Either a basic one that takes a string
raise = function(msg) { throw new Error(msg) }
true || raise("some_var not defined")
// One that takes an error
raise = function(error) { throw error }
true || raise(new Error("some_var not defined"))
// Or one that can take either - I'm not sure of whether you would
// want different errors raised etc. I don't know JS well enough for that.
raise = function(error) {
if(typeof(error) == "string")
throw new Error(error)
else
throw error
}
true || raise("some_var not defined")
true || raise(new Error("some_var not defined"))
//--
// Suggestion 2: Wrap the whole thing in a function
//--
do_or_throw = function(thing, msg) {
if(typeof(thing) == "function") { thing = thing() }
if(thing) { return thing }
throw new Error(msg)
}
do_or_throw(function() { return true }, "some_var not defined") // Where you want to pass a function, or have a computation
do_or_throw(true, "some_var not defined") // Where you're not evaluating anything
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment