enkot / catch-decorator

Allows you to handle exceptions in ECMAScript/Typescript classes with only one annotation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

support default return value

Link631 opened this issue · comments

It would be great, if a default return value could be supported.

Hi, i am currently not able to submit a pull request.

I changed the code to following, which makes it possible to return a value in the handlerfunction. it still works for void and async methods.

type HandlerFunction = (error: any, ctx: any) => any;

`type HandlerFunction = (error: any, ctx: any) => any;

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
}

}`