This commit is contained in:
手瓜一十雪
2025-01-03 21:07:26 +08:00
parent 5c91dbd819
commit c499858a5a
2 changed files with 31 additions and 24 deletions

View File

@@ -1,7 +1,13 @@
type Handler<T> = () => T | Promise<T>;
type Checker<T> = (result: T) => T | Promise<T>;
export class Fallback<T> {
private handlers: Handler<T>[] = [];
private checker: Checker<T>;
constructor(checker?: Checker<T>) {
this.checker = checker || (async (result: T) => result);
}
add(handler: Handler<T>): this {
this.handlers.push(handler);
@@ -14,8 +20,10 @@ export class Fallback<T> {
for (const handler of this.handlers) {
try {
const result = await handler();
if (result !== undefined) {
return result;
try {
return await this.checker(result);
} catch (checkerError) {
errors.push(checkerError instanceof Error ? checkerError : new Error(String(checkerError)));
}
} catch (error) {
errors.push(error instanceof Error ? error : new Error(String(error)));
@@ -23,4 +31,13 @@ export class Fallback<T> {
}
throw new AggregateError(errors, 'All handlers failed');
}
}
export class FallbackUtil{
static boolchecker<T>(value: T, condition: boolean): T {
if (condition) {
return value;
} else {
throw new Error('Condition is false, throwing error');
}
}
}