Skip to content

Commit

Permalink
fix(execLocally): re-throw errors for local dev (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
charlypoly authored Dec 11, 2023
1 parent 5f22621 commit a9055df
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/tidy-days-tease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@defer/client": patch
---

Re-throw errors for local development
20 changes: 13 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,22 @@ export const deferEnabled = () => !!getEnv("DEFER_TOKEN");
async function execLocally(
id: string,
fn: any,
args: any
args: any,
shouldThrowErrors = false
): Promise<client.FetchExecutionResponse> {
let state: client.ExecutionState = "succeed";
let originalResult: any;
let executionError: Error | undefined;
try {
originalResult = await fn(...args);
} catch (error) {
const e = error as Error;
executionError = error as Error;
state = "failed";
originalResult = {
name: e.name,
message: e.message,
cause: e.cause,
stack: e.stack,
name: executionError.name,
message: executionError.message,
cause: executionError.cause,
stack: executionError.stack,
};
}

Expand All @@ -62,6 +64,10 @@ async function execLocally(
const response = { id, state, result };
__database.set(id, response);

if (executionError && shouldThrowErrors) {
throw executionError;
}

return response;
}

Expand Down Expand Up @@ -105,7 +111,7 @@ async function enqueue<F extends DeferableFunction>(

const id = randomUUID();
__database.set(id, { id: id, state: "started" });
execLocally(id, originalFunction, functionArguments);
execLocally(id, originalFunction, functionArguments, true);
return { id };
}

Expand Down
16 changes: 16 additions & 0 deletions tests/awaitResult.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { awaitResult, defer } from "../src";
import { DeferError } from "../src/errors";
import { makeHTTPClient } from "../src/httpClient";
import { jitter } from "../src/jitter";

Expand Down Expand Up @@ -61,4 +62,19 @@ describe("awaitResult(deferFn)", () => {
});
});
});

describe("when Defer is inactive (`DEFER_TOKEN` is unset)", () => {
beforeAll(() => {
process.env["DEFER_TOKEN"] = "";
});
it("should rethrow any error as `DeferError`", async () => {
const myFunction = async (_str: string) => {
throw new Error("my function failed locally!");
};
const deferred = defer(myFunction);
const awaitable = awaitResult(deferred);

await expect(awaitable("")).rejects.toThrow(DeferError);
});
});
});

0 comments on commit a9055df

Please sign in to comment.