Synchronous solution
Use the following type-safe utility function:
function tryGet<T>(getter: () => T): {
success: true;
value: T;
} | {
success: false;
error: Error;
} {
try {
return {
success: true,
value: getter(),
};
} catch (error) {
return {
success: false,
error: error as Error,
};
}
}
Usage:
const result = tryGet(getValue);
if (!result.success) {
report(result.error);
return;
}
use(result.value);
Asynchronous solution
export default async function tryGetAsync<T>(
getter: () => Promise<T>
): Promise<{
success: true;
result: T;
} | {
success: false;
error: Error;
}> {
try {
return {
success: true,
result: await getter(),
};
} catch (error) {
return {
success: false,
error: error as Error,
};
}
}
Usage:
const result = await tryGetAsync(fetchValue);
if (!result.success) {
report(result.error);
return;
}
use(result.value);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…