Last active
March 25, 2019 15:08
-
-
Save nucleartide/c12f5deec2a25ebcdc8d103dc4351fa9 to your computer and use it in GitHub Desktop.
Explicit Go-style error handling with ES6 destructuring. No more try-catch!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
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
For handling promises: