Skip to content Skip to sidebar Skip to footer

How To Wrap Errors From Third Party Api?

I do use a third party API to manage auth operations. The available methods returns promises, suppose a createUser method, I can call it this way: this.auth.createUser(data).then((

Solution 1:

Use resolve and reject in promise.

Here (your code):

try {
    return originalFunction.apply(this, arguments); // asynchronous because of setTimeOut
} catch (e) {
    this.log('error', e);
    thrownewError('error-auth-' + nameFunctionAsTag(key));
}
// 3 second later, trigger exception out of try/catch statement

What you can do:

functionasyncError(){
    returnnewPromise(function(resolve, reject){
        // ... codereject(newError('Error ...'));
        // ... code
    })

}

asyncfunctiontest(){
    try{
        const experiment = awaitasyncError();
    }
    catch(e){
        console.log(e)
    }
}

Other way (catch without waiting):

functiontest2(){
    asyncError().catch((e) =>console.log(e));
}

Solution 2:

When you register a Promise, or even a setTimeout you are not calling that function within the same stack context. You are essentially telling the engine to register a callback and the system will invoke it with the correct parameters at a later time. Because of this, the error never bubbles up to a try/catch. You can utilize the await keyword inside an async function to suspend execution and return at a later time, maintaining the same context, which would retain the try/catch blocks use here. This is what you need to do here. Check out: https://levelup.gitconnected.com/the-definite-guide-to-handling-errors-gracefully-in-javascript-58424d9c60e6

Solution 3:

Just found the main problem: Object.keys(auth) returns empty array over class instance.

After changing it to Object.getOwnPropertyNames(Object.getPrototypeOf(auth)) I could focus on the promise thing you all helped me out :)

My final working snippet ended this way:

classAuth {
    createUser(...args) {
        returnPromise.resolve().then(() => {
            this.log(...args);
            thrownewError('auth service throws some error with a lot of details and info not user friendly');
        });
    }
    log(...args) { console.log('this', ...args) }
}

const auth = newAuth();

Object.getOwnPropertyNames(Object.getPrototypeOf(auth)).forEach(key => {
    if (key === 'constructor') return;

    if (typeof auth[key] === 'function') {
        const originalFunction = auth[key];
        auth[key] = function() {
            returnPromise.resolve()
                .then(() => originalFunction.apply(this, arguments))
                .catch(e => {
                    this.log('error', e.message);
                    thrownewError('error-auth-' + nameFunctionAsTag(key));
                });
        };
    }
});

functionnameFunctionAsTag(name) {
    return name.replace(/(?!^)[A-Z]/g, c =>'-' + c.toLowerCase());
}

auth.log('auth service');
auth.createUser(1, 2, 3, 4, 5).catch(e =>console.log('final error:', e.message));

Thank you all for the help :)

Post a Comment for "How To Wrap Errors From Third Party Api?"