async-lock icon indicating copy to clipboard operation
async-lock copied to clipboard

Recognise async lock errors

Open nebarf opened this issue 1 year ago • 1 comments

Hi @rogierschouten! Thanks for keeping to work on this library, really appreciate :pray:

Correct me if I'm wrong, currently the only way to distinguish between async-lock errors and any error that's thrown by the wrapped async function is by using the error message:

function someAsyncFn() {}

lock.acquire(key, someAsyncFn, opts)
    .catch(function(err) {
        const isAsyncLockTimeoutError = err instanceof Error && err.message.includes('async-lock timed out')
	if (isAsyncLockTimeoutError) {
            // handle async-lock timeout error
        }
    });

IMHO it would be great if async-lock could deal with its own error classes to model anything can go wrong on the library side.

class AsyncLockError extends Error {
    constructor(message) {
        super(message);
    }
}

class AsyncLockTimeoutError extends AsyncLockError {
    constructor(queueKey) {
        super(`Async lock timeout out in queue ${async-lock timed out in queue}`);
        this.name = 'AsyncLockTimeoutError';
    }
}

This mean on the user-land side it would be much cleaner handling any async-lock error:

function someAsyncFn() {}

lock.acquire(key, someAsyncFn, opts)
    // Handle different kind of async-lock errors
    .catch(function(err) {
        if (err instanceof AsyncLockTimeoutError) {
            // do something...
        }
        if (err instanceof AsyncLockMaxOccTimeError) {
            // do something...
        }
    });
function someAsyncFn() {}

lock.acquire(key, someAsyncFn, opts)
    // Catch any kind of async-lock errors
    .catch(function(err) {
        if (err instanceof AsyncLockError) {
            // async-lock error
        } else {
            // Any error thrown by `someAsyncFn`
        }
    });

What do you think about that? I can find some time to work on this if it can help.

nebarf avatar Mar 22 '23 17:03 nebarf

Would be great, I'll merge a PR. Sorry for late reply, this year's been rough

rogierschouten avatar Dec 22 '23 19:12 rogierschouten