Last active
August 30, 2023 09:53
-
-
Save zerkalica/54da872416357c7a4631836b17cc49e3 to your computer and use it in GitHub Desktop.
safe_errors
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
namespace $ { | |
const cache = new WeakMap<Object, Map<PropertyKey, Function>>() | |
function $gd_rad_error_safe_prop<Host, Args extends unknown[]>( this: Host, val: (this: Host, ...args: Args) => unknown, ...args: Args ) { | |
try { | |
let result = val.call(this, ...args) | |
if ($mol_promise_like(result)) { | |
result = result.catch( | |
err => err instanceof Error ? | |
err : | |
new Error(String(err), { cause: err }) | |
) | |
} | |
return result | |
} catch (e) { | |
if (! $mol_promise_like(e) && ! (e instanceof Error)) { | |
e = new Error(String(e), { cause: e }) | |
} | |
$mol_fail_hidden(e) | |
} | |
} | |
export function $gd_rad_error_safe< Host extends object >( obj: Host ) { | |
return new Proxy( obj, { | |
get( obj, field ) { | |
const val = (obj as any)[ field ] | |
if( typeof val !== 'function' ) return val | |
let methods = cache.get(obj) | |
if (! methods) cache.set(obj, methods = new Map()) | |
let patched = methods.get(field) | |
if (! patched) methods.set(field, patched = $gd_rad_error_safe_prop.bind(obj, val)) | |
return patched | |
}, | |
apply( obj, self, args ) { | |
return $gd_rad_error_safe_prop.call(obj, self, ...args) | |
} | |
} ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment