You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function handleError(
ctx: any,
errorClass: any,
handler: HandlerFunction,
error: any
) {
// check if error is instance of passed error class
if (typeof handler === 'function' && error instanceof errorClass) {
// run handler with error object
// and class context as second argument
return handler.call(null, error, ctx)
} else {
// throw error further,
// next decorator in chain can catch it
throw error
}
}
// decorator factory function
export function myCatch(errorClass: any, handler: HandlerFunction): 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) => {
return handleError(this, errorClass, handler, error)
})
}
// return actual result
return result
} catch (error) {
return handleError(this, errorClass, handler, error)
}
}
return descriptor
}
It would be great, if a default return value could be supported.
The text was updated successfully, but these errors were encountered: