处理类方法内的异常

问题描述 投票:0回答:1

我想知道是否有一种方法可以处理类方法中发生的错误异常,而不是在类方法中使用 try catch 包装代码片段。

找到了带有装饰器的解决方案,但不确定它是否提供相同的功能。

typescript exception decorator
1个回答
0
投票

我相信你的意思是这样的:

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
        }
    };
}

使用示例:

class MyService {
    constructor(private queueService: QueueService) {}

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

这是一种无需装饰器的方法,我不确定你想要哪种:

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});
        // ...
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.