Skip to content

Instantly share code, notes, and snippets.

@nucleartide
Last active March 25, 2019 15:08
Show Gist options
  • Save nucleartide/c12f5deec2a25ebcdc8d103dc4351fa9 to your computer and use it in GitHub Desktop.
Save nucleartide/c12f5deec2a25ebcdc8d103dc4351fa9 to your computer and use it in GitHub Desktop.
Explicit Go-style error handling with ES6 destructuring. No more try-catch!
function explicit(ctx, fn) {
return function() {
try {
const result = fn.apply(ctx, arguments)
return [null, result]
} catch (err) {
return [err, null]
}
}
}
function explicitAsync(ctx, fn) {
return function* () {
try {
const result = yield fn.apply(ctx, arguments)
return [null, result]
} catch (err) {
return [err, null]
}
}
}
// API usage
JSON.explicitParse = explicit(null, JSON.parse)
const explicitAsyncFn = explicitAsync(component, someAsyncFn)
// sync example
const [err, json] = JSON.explicitParse('this will fail lol')
if (err) {
// handle error here
}
// async example
const [err, result] = yield* explicitAsyncFn()
if (err) {
// handle error here
}
@nucleartide
Copy link
Author

For handling promises:

module.exports = function explicit(promise) {
  return promise
    .then(value => [null, value])
    .catch(reason => [reason, null])
}

@nucleartide
Copy link
Author

co(function*() {
  const [err, res] = yield explicit(somePromise)
  if (err) {
    // handle error
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment