Skip to content

Instantly share code, notes, and snippets.

@eralston
Created July 31, 2020 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eralston/9c24dd306b7910c803908889db77c9cf to your computer and use it in GitHub Desktop.
Save eralston/9c24dd306b7910c803908889db77c9cf to your computer and use it in GitHub Desktop.
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