Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support default return value #12

Open
Link631 opened this issue Mar 28, 2020 · 1 comment
Open

support default return value #12

Link631 opened this issue Mar 28, 2020 · 1 comment

Comments

@Link631
Copy link

Link631 commented Mar 28, 2020

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

@Link631
Copy link
Author

Link631 commented Mar 28, 2020

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
}

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant