Created
June 7, 2020 18:09
-
-
Save JakeTheCorn/39cc7b8bbce7ffde04d5dd5a0a963a71 to your computer and use it in GitHub Desktop.
little idea for a data structure that forces callers to deal with error state
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
class Errorable { | |
constructor({ value = null, error = null }) { | |
this.__value = value | |
// should this be only instance of Error or null validated? | |
this.__err = error | |
this.__err_accessed = false | |
} | |
static wrapSync(fn) { | |
return (...args) => { | |
try { | |
const value = fn(...args) | |
return new Errorable({ value }) | |
} catch (error) { | |
return new Errorable({ error }) | |
} | |
} | |
} | |
static wrap(fn) { | |
return async (...args) => { | |
try { | |
const value = await fn(...args) | |
return new Errorable({ value }) | |
} catch (error) { | |
return new Errorable({ error }) | |
} | |
} | |
} | |
// abstract | |
call(...args) { | |
// just throw a string, stack traces | |
throw new Error('Not Implemented') | |
} | |
get value() { | |
if (!this.__err_accessed) { | |
// specific error would be better | |
throw new Error('Cannot access value until error has been accessed') | |
} | |
return this.__value | |
} | |
get error() { | |
this.__err_accessed = true | |
return this.__err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment