Skip to content

Commit

Permalink
Switch to throw marker to allow throwing scalars
Browse files Browse the repository at this point in the history
  • Loading branch information
surma committed Apr 27, 2020
1 parent 911d2d2 commit a88f600
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 23 deletions.
35 changes: 16 additions & 19 deletions src/comlink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export { Endpoint };
export const proxyMarker = Symbol("Comlink.proxy");
export const createEndpoint = Symbol("Comlink.endpoint");
export const releaseProxy = Symbol("Comlink.releaseProxy");
const throwSet = new WeakSet();
const throwMarker = Symbol("Comlink.thrown");

// prettier-ignore
type Promisify<T> =
Expand Down Expand Up @@ -100,24 +100,23 @@ export const transferHandlers = new Map<string, TransferHandler>([
[
"throw",
{
canHandle: obj => throwSet.has(obj),
serialize(obj) {
const isError = obj instanceof Error;
let serialized = obj;
canHandle: obj => typeof obj === "object" && throwMarker in obj,
serialize({ value }) {
const isError = value instanceof Error;
let serialized = { isError, value };
if (isError) {
serialized = {
isError,
message: obj.message,
stack: obj.stack
serialized.value = {
message: value.message,
stack: value.stack
};
}
return [serialized, []];
},
deserialize(obj) {
if ((obj as any).isError) {
throw Object.assign(new Error(), obj);
deserialize(serialized) {
if (serialized.isError) {
throw Object.assign(new Error(), serialized.value);
}
throw obj;
throw serialized.value;
}
}
]
Expand Down Expand Up @@ -173,14 +172,12 @@ export function expose(obj: any, ep: Endpoint = self as any) {
}
break;
}
} catch (e) {
returnValue = e;
throwSet.add(e);
} catch (value) {
returnValue = { value, [throwMarker]: 0 };
}
Promise.resolve(returnValue)
.catch(e => {
throwSet.add(e);
return e;
.catch(value => {
return { value, [throwMarker]: 0 };
})
.then(returnValue => {
const [wireValue, transferables] = toWireValue(returnValue);
Expand Down
8 changes: 4 additions & 4 deletions tests/same_window.comlink.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ describe("Comlink in the same realm", function() {
await thing();
throw "Should have thrown";
} catch (err) {
expect(err).to.not.eq("Should have thrown");
expect(err).to.not.equal("Should have thrown");
expect(err.test).to.equal(true);
}
});
Expand All @@ -156,9 +156,9 @@ describe("Comlink in the same realm", function() {
await thing();
throw "Should have thrown";
} catch (err) {
expect(err).to.not.eq("Should have thrown");
expect(err).to.be("oops");
expect(typeof err).to.be("string");
expect(err).to.not.equal("Should have thrown");
expect(err).to.equal("oops");
expect(typeof err).to.equal("string");
}
});

Expand Down

0 comments on commit a88f600

Please sign in to comment.