mirror of
https://git.um-react.app/um/um-react.git
synced 2025-11-28 11:33:02 +00:00
feat: friendly way to inform user there's an error (#12)
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user