refactor(doTimed): refactor error handling and skip timing when not in dev mode
This commit is contained in:
parent
b7cac5724d
commit
fd06160f7e
1 changed files with 36 additions and 15 deletions
|
|
@ -4,6 +4,7 @@ import { v7 } from 'uuid';
|
||||||
export const InvisibleCodec = baseCodecFrom(InvisibleDictionary);
|
export const InvisibleCodec = baseCodecFrom(InvisibleDictionary);
|
||||||
|
|
||||||
export function doTimed<T>(message: string, callback: () => T): T {
|
export function doTimed<T>(message: string, callback: () => T): T {
|
||||||
|
if (import.meta.env.DEV) {
|
||||||
const hiddenId = InvisibleCodec.encode(v7());
|
const hiddenId = InvisibleCodec.encode(v7());
|
||||||
console.time(message + hiddenId);
|
console.time(message + hiddenId);
|
||||||
try {
|
try {
|
||||||
|
|
@ -12,15 +13,35 @@ export function doTimed<T>(message: string, callback: () => T): T {
|
||||||
} finally {
|
} finally {
|
||||||
console.timeEnd(message + hiddenId);
|
console.timeEnd(message + hiddenId);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
return callback();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function doTimedAsync<T>(message: string, callback: () => T): Promise<Awaited<T>> {
|
export function doTimedAsync<T, R = T extends Promise<T> ? Promise<T> : T>(
|
||||||
|
message: string,
|
||||||
|
callback: () => R,
|
||||||
|
throwError: boolean = false
|
||||||
|
): R {
|
||||||
|
if (import.meta.env.DEV) {
|
||||||
|
return new Promise(async (resolve, reject) => {
|
||||||
const hiddenId = InvisibleCodec.encode(v7());
|
const hiddenId = InvisibleCodec.encode(v7());
|
||||||
console.time(message + hiddenId);
|
console.time(message + hiddenId);
|
||||||
try {
|
try {
|
||||||
const output = await callback();
|
const output = await callback();
|
||||||
return output;
|
resolve(output);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Error in timed operation "${message}":`, err);
|
||||||
|
if (throwError) {
|
||||||
|
reject(err);
|
||||||
|
} else {
|
||||||
|
resolve(undefined as R);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
console.timeEnd(message + hiddenId);
|
console.timeEnd(message + hiddenId);
|
||||||
}
|
}
|
||||||
|
}) as R;
|
||||||
|
} else {
|
||||||
|
return callback() as R;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue