Created
September 19, 2022 19:11
-
-
Save doronguttman/873d37d1d1373a4450f719a77fa866e1 to your computer and use it in GitHub Desktop.
Wrap method with try-catch
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
const WithTryCatch: MethodDecorator = function <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void { | |
const org = descriptor.value as (...args: any[]) => any; | |
if (typeof org !== "function") { return; } | |
descriptor.value = function () { | |
try { | |
console.debug(`withTryCatch: ${String(propertyKey)} trying...`); | |
let result = org.apply(target, Array.from(arguments)); | |
if (result instanceof Promise) { | |
return result | |
.then(r => { | |
console.debug(`withTryCatch: ${String(propertyKey)} success`); | |
return r; | |
}) | |
.catch(e => { | |
console.error(`withTryCatch: ${String(propertyKey)} error`, e); | |
return undefined; | |
}); | |
} | |
console.debug(`withTryCatch: ${String(propertyKey)} success`); | |
return result; | |
} catch (e) { | |
console.error(`withTryCatch: ${String(propertyKey)} error`, e); | |
return undefined; | |
} | |
} as T; | |
Object.defineProperty(target, propertyKey, descriptor); | |
} | |
function wait(time: number) { | |
return new Promise(resolve => setTimeout(resolve, time)); | |
} | |
class Foo { | |
public unwrapped() { | |
console.log("unwrapped"); | |
throw new Error("waaa!"); | |
} | |
@WithTryCatch | |
public wrapped() { | |
console.log("wrapped"); | |
throw new Error("weee!"); | |
} | |
public async unwrappedAsync() { | |
await wait(1000); | |
console.log("unwrappedAsync"); | |
throw new Error("waaa!"); | |
} | |
@WithTryCatch | |
public async wrappedAsync() { | |
await wait(1000); | |
console.log("wrappedAsync"); | |
throw new Error("weee!"); | |
} | |
} | |
const foo = new Foo(); | |
try { | |
console.log(foo.wrapped()); | |
} catch (e) { | |
console.debug("uncaught error", e); | |
} | |
try { | |
console.log(foo.unwrapped()); | |
} catch (e) { | |
console.debug("uncaught error", e); | |
} | |
(async () => { | |
try { | |
console.log(await foo.wrappedAsync()); | |
} catch (e) { | |
console.debug("uncaught error", e); | |
} | |
try { | |
console.log(await foo.unwrappedAsync()); | |
} catch (e) { | |
console.debug("uncaught error", e); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment