Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions src/WorkerError.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,45 @@
const stack = (err, worker, workerId) => {
const originError = (err.stack || '')
// Utility function to safely build a merged stack trace
const buildStackTrace = (err, workerStack = '', workerId = 'unknown') => {
const originStackLines = (err?.stack || '')
.split('\n')
.filter((line) => line.trim().startsWith('at'));

const workerError = worker
const workerStackLines = (workerStack || '')
.split('\n')
.filter((line) => line.trim().startsWith('at'));

const diff = workerError
.slice(0, workerError.length - originError.length)
// Compute the difference between the worker's stack and the error's stack
const extraWorkerLines = workerStackLines.slice(
0,
Math.max(0, workerStackLines.length - originStackLines.length)
);

// Build a readable, merged stack trace
const mergedStack = [
`Thread Loader (Worker ${workerId})`,
err?.message || 'Unknown error',
extraWorkerLines.join('\n'),
...originStackLines
]
.filter(Boolean)
.join('\n');

originError.unshift(diff);
originError.unshift(err.message);
originError.unshift(`Thread Loader (Worker ${workerId})`);

return originError.join('\n');
return mergedStack;
};

class WorkerError extends Error {
constructor(err, workerId) {
super(err);
this.name = err.name;
this.message = err.message;
// Pass a safe message to the base Error class
super(err?.message || 'Unknown worker error');

this.name = err?.name || 'WorkerError';
this.originalError = err;

Error.captureStackTrace(this, this.constructor);
// Capture the current stack before modifying it
Error.captureStackTrace?.(this, WorkerError);

this.stack = stack(err, this.stack, workerId);
// Replace the default stack with a combined one
this.stack = buildStackTrace(err, this.stack, workerId);
}
}

Expand Down