Skip to content

Instantly share code, notes, and snippets.

@asvny
Created August 31, 2018 02:41
Show Gist options
  • Save asvny/82740250a56829b972368478a1c68014 to your computer and use it in GitHub Desktop.
Save asvny/82740250a56829b972368478a1c68014 to your computer and use it in GitHub Desktop.
Catch decorator in typescript
function Catch(E, callback) {
return function (target, key: string, descriptor: PropertyDescriptor) {
if(descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, key);
}
var originalMethod = descriptor.value;
descriptor.value = function () {
try {
originalMethod()
} catch (err) {
if (err instanceof E) {
callback(err);
}
}
};
return descriptor;
}
}
// example
class App {
static function reap() {
console.log('ya hoo')
}
@Catch(Error, e => console.log('bad happened'))
renderJSON() {
throw new Error('hallo');
}
}
(new App()).renderJSON();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment