Skip to content

Commit 62bc83f

Browse files
authored
Merge pull request #33 from phil-lgr/serialize-error
Handle error thrown in worker (passing as object then calling Error() again)
2 parents 7b25e3d + f8dc9e5 commit 62bc83f

File tree

4 files changed

+27
-7
lines changed

4 files changed

+27
-7
lines changed

src/rpc-worker-loader.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@ function workerSetup() {
1010
else {
1111
p = Promise.reject('No such method');
1212
}
13-
p.then(
14-
result => {
13+
p.then(result => {
1514
postMessage({ type: 'RPC', id, result });
16-
},
17-
error => {
15+
})
16+
.catch(error => {
17+
if (error.stack) {
18+
postMessage({ type: 'RPC', id, error: { name: error.name, message: error.message, stack: error.stack } });
19+
return;
20+
}
1821
postMessage({ type: 'RPC', id, error });
1922
});
2023
}
@@ -26,4 +29,4 @@ const workerScript = '\n' + Function.prototype.toString.call(workerSetup).replac
2629

2730
export default function rpcWorkerLoader(content) {
2831
return content + workerScript;
29-
}
32+
}

src/rpc-wrapper.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@ export default function addMethods(worker, methods) {
88
let f = callbacks[d.id];
99
if (f) {
1010
delete callbacks[d.id];
11-
if (d.error) f[1](d.error);
11+
if (d.error) {
12+
let workerError = Error(d.error && d.error.message ? d.error.message : 'Error in worker');
13+
if (d.error && d.error.stack) workerError.stack = d.error.stack;
14+
if (d.error && d.error.name) workerError.name = d.error.name;
15+
f[1](workerError);
16+
}
1217
else f[0](d.result);
1318
}
1419
}

test/src/index.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ describe('worker', () => {
1919
expect(out).toEqual('a [bar:3] b');
2020
});
2121

22+
it('worker.throwError() should pass the Error back to the application context', async () => {
23+
try {
24+
let out = await worker.throwError();
25+
} catch (e) {
26+
expect(e).toEqual(new Error('Error in worker.js'));
27+
}
28+
});
29+
2230
it('should fire ready event', done => {
2331
let worker = new Worker(),
2432
called = false,

test/src/worker.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ export function foo() {
66
return 1;
77
}
88

9+
export function throwError() {
10+
throw new Error('Error in worker.js');
11+
}
12+
913
export function bar(a, b) {
1014
return `${a} [bar:${otherBar}] ${b}`;
11-
}
15+
}

0 commit comments

Comments
 (0)