feat: friendly way to inform user there's an error (#12)

This commit is contained in:
鲁树人
2023-05-22 22:24:41 +01:00
parent 4aff3b7a07
commit 52d86e4601
8 changed files with 99 additions and 19 deletions

View File

@@ -1,15 +1,15 @@
import { nextTickAsync } from './nextTick';
export abstract class ConcurrentQueue<T, R = unknown> {
protected items: [T, (result: R) => void, (error: unknown) => void][] = [];
protected items: [T, (result: R) => void, (error: unknown) => void, void | (() => void)][] = [];
constructor(protected maxConcurrent = 5) {}
abstract handler(item: T): Promise<R>;
public async add(item: T): Promise<R> {
public async add(item: T, onPreProcess?: () => void): Promise<R> {
return new Promise((resolve, reject) => {
this.items.push([item, resolve, reject]);
this.items.push([item, resolve, reject, onPreProcess]);
this.runWorkerIfFree();
});
}
@@ -32,9 +32,11 @@ export abstract class ConcurrentQueue<T, R = unknown> {
private async processQueue() {
let item: (typeof this.items)[0] | void;
while ((item = this.items.shift())) {
const [payload, resolve, reject] = item;
const [payload, resolve, reject, onPreProcess] = item;
try {
onPreProcess?.();
resolve(await this.handler(payload));
} catch (error: unknown) {
reject(error);

View File

@@ -1,10 +1,12 @@
import { nanoid } from 'nanoid';
import { DecryptError } from '~/decrypt-worker/util/DecryptError';
type WorkerServerHandler<P, R> = (payload: P) => R | Promise<R>;
interface SerializedError {
message: string;
stack?: string;
code?: string;
}
interface WorkerClientRequestPayload<P = unknown> {
@@ -39,6 +41,7 @@ export class WorkerClientBus<T = string> {
if (error) {
const wrappedError = new Error(error.message, { cause: error });
wrappedError.stack = error.stack;
Object.assign(wrappedError, { code: error.code ?? null });
reject(wrappedError);
} else {
resolve(result as never);
@@ -77,8 +80,12 @@ export class WorkerServerBus {
} else {
try {
result = await handler(payload);
} catch (e: unknown) {
error = e;
} catch (err: unknown) {
if (err instanceof DecryptError) {
error = err.toJSON();
} else {
error = err;
}
}
}