Search code examples
typescriptexceptiondecorator

Handle exceptions inside class method


I am wondering if there is a way to handle error exceptions that occures inside class method other way than having try catch wrapped code snippet inside class method.

Found solution with decorators, but not sure it provides same functionality.


Solution

  • I believe that you mean like this:

    function CatchError(target: any, propertyName: string, descriptor: PropertyDescriptor) {
        const method = descriptor.value;
    
        descriptor.value = function (...args: any[]) {
            try {
                return method.apply(this, args);
            } catch (error) {
                console.error(`Error occurred in ${propertyName}:`, error);
                // Handle the error or rethrow it
                // You can also perform specific actions based on error type
            }
        };
    }
    

    example of use:

    class MyService {
        constructor(private queueService: QueueService) {}
    
        @CatchError
        handleCreateQueue(data: any) {
            const queue = this.queueService.create({...data});
            // Other operations...
        }
    }
    

    Here is a way to do it without decorators, I am not sure which one you wanted:

    function withErrorHandling(fn: Function) {
        return function(...args: any[]) {
            try {
                return fn.apply(this, args);
            } catch (error) {
                console.error("Error occurred:", error);
                // Handle the error or rethrow it
            }
        };
    }
    
    class MyService {
        handleCreateQueue = withErrorHandling((data: any) => {
            // Your method implementation
            const queue = this.queueService.create({...data});
            // ...
        });
    }