Skip to content

Instantly share code, notes, and snippets.

@zjhiphop
Forked from eiriklv/avoiding-exceptions.js
Created February 5, 2017 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zjhiphop/3c68c197e5a75f36f635afbb243d9d45 to your computer and use it in GitHub Desktop.
Save zjhiphop/3c68c197e5a75f36f635afbb243d9d45 to your computer and use it in GitHub Desktop.
Exception free JavaScript?
/**
* 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 => [null, result])
.catch(error => [error, null]);
}
/**
* 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 = null;
let result = null;
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