Created
August 31, 2018 02:41
-
-
Save asvny/82740250a56829b972368478a1c68014 to your computer and use it in GitHub Desktop.
Catch decorator in typescript
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
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