Last active
February 2, 2019 12:13
-
-
Save eiriklv/1fb4af8a268b394ddce5b8e4623bc546 to your computer and use it in GitHub Desktop.
Exception free JavaScript?
This file contains hidden or 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
/** | |
* WHY? - BECAUSE EXCEPTIONS/TRY/CATCH IS A GLOBAL HORRIBLE MESS :-( | |
* Check out error handling in golang: https://blog.golang.org/error-handling-and-go | |
*/ | |
/** | |
* Wrap an "unsafe" promise | |
*/ | |
function safePromise(promise) { | |
return promise | |
.then(result => [undefined, result]) | |
.catch(error => [error, undefined]); | |
} | |
/** | |
* Wrap an "unsafe" function that might throw | |
* upon execution in a function that returns | |
* a promise (which is handled "safely" with safePromise) | |
* | |
* NOTE: This will only handle throws that | |
* are done within the same execution tick, | |
* and not errors that are thrown "later" | |
* within the same context (no way to do that..) | |
*/ | |
function safeFunction(fn) { | |
return function(...args) { | |
let error = undefined; | |
let result = undefined; | |
try { | |
result = fn.apply(this, args); | |
} catch (e) { | |
error = e; | |
} | |
return safePromise(error ? Promise.reject(error) : Promise.resolve(result)); | |
} | |
} | |
/** | |
* Example of promise returning function that rejects | |
*/ | |
function getAsset(id) { | |
return Promise.reject(new Error('Booo!')); | |
} | |
/** | |
* Example use with async/await | |
*/ | |
async function letsDoThis() { | |
// Alt 1 (wrapping a promise returning function) | |
const [error, result] = await safeFunction(getAsset)(10); | |
// Alt 2 (wrapping a promise) | |
const [error, result] = await safePromise(getAsset(10)); | |
if (error) { | |
/** | |
* Handle the error appropriately | |
* (You could of course just throw it here if you wanted to - but it is at least optional) | |
*/ | |
} | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@tiansh - I'm just showing two ways of achieving the same thing ✌️️