Skip to content

Commit

Permalink
(#556) Store intermediate results and errors to provide additional co…
Browse files Browse the repository at this point in the history
…ntext on timeout
  • Loading branch information
s1hofmann committed Feb 3, 2024
1 parent 67a413a commit 6161475
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/util/timeout.function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ export function timeout<R>(
updateIntervalMs: number,
maxDurationMs: number,
action: (...params: any) => Promise<R>,
config?: TimoutConfig
config?: TimoutConfig,
): Promise<R> {
return new Promise<R>((resolve, reject) => {
let interval: NodeJS.Timeout;
let timerCleaned = false;
let lastResult: R | null;
let lastRejectionReason: any | null;

if (config?.signal) {
config.signal.onabort = () => {
Expand All @@ -29,12 +31,16 @@ export function timeout<R>(
if (!result && !timerCleaned) {
interval = setTimeout(executeInterval, updateIntervalMs);
} else {
lastResult = result;
lastRejectionReason = null;
cleanupTimer();
resolve(result);
}
}

function handleRejection() {
function handleRejection(reason: any) {
lastRejectionReason = reason;
lastResult = null;
if (!timerCleaned) {
interval = setTimeout(executeInterval, updateIntervalMs);
}
Expand All @@ -52,7 +58,17 @@ export function timeout<R>(

const maxTimeout = setTimeout(() => {
cleanupTimer();
reject(`Action timed out after ${maxDurationMs} ms`);
let additionalInformation: string | undefined;
if (lastResult == null && lastRejectionReason != null) {
additionalInformation = `Last rejection reason was: ${lastRejectionReason}.`;
} else if (lastResult == null && lastRejectionReason == null) {
additionalInformation = `Didn't receive a result within timeout.`;
}
reject(
`Action timed out after ${maxDurationMs} ms.${
additionalInformation ? ` ${additionalInformation}` : ""
}`,
);
}, maxDurationMs);

executeInterval();
Expand Down

0 comments on commit 6161475

Please sign in to comment.