Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created June 7, 2020 18:09
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 JakeTheCorn/39cc7b8bbce7ffde04d5dd5a0a963a71 to your computer and use it in GitHub Desktop.
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
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