Created
July 31, 2020 18:46
-
-
Save eralston/9c24dd306b7910c803908889db77c9cf to your computer and use it in GitHub Desktop.
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
import PublicError from './PublicError'; | |
// Based catch-decorator by Enkot https://github.com/enkot/catch-decorator | |
// decorator factory function | |
export default (name: string, message?: string): any => { | |
return ( | |
target: any, | |
propertyKey: string, | |
descriptor: PropertyDescriptor, | |
) => { | |
// save a reference to the original method | |
const originalMethod = descriptor.value | |
// rewrite original method with custom wrapper | |
descriptor.value = function (...args: any[]) { | |
try { | |
const result = originalMethod.apply(this, args) | |
// check if method is asynchronous | |
if (result && typeof result.then === 'function' && typeof result.catch === 'function') { | |
// return promise | |
return result.catch((error: any) => { | |
// TODO | |
if (error instanceof PublicError) | |
throw error; | |
throw new PublicError(error, name, message); | |
}) | |
} | |
// return actual result | |
return result | |
} catch (error) { | |
throw new PublicError(error, name, message); | |
} | |
} | |
return descriptor | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment