attempt()
attempt<
T>(func, ...args):Error|T
Attempts to invoke func, returning either the result or the caught error.
๐ Why is this a Hidden Gem?
Wrap any function call in a try/catch and get either the result or the error.
Use try/catch directly or Zygos Result pattern instead.
Type Parametersโ
T: Tโ
The return type of the function.
Parametersโ
func: (...args) => Tโ
The function to attempt.
args: ...unknown[]โ
The arguments to invoke the function with.
Returns: Error | Tโ
The result of the function or the caught error.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
attempt (Lodash, es-toolkit) ยท try (Effect) ยท tryCatch (Ramda) ยท tryit (Radashi) ยท โ (Remeda, Modern Dash, Antfu)
Exampleโ
// โ Deprecated approach
const result = attempt(JSON.parse, '{"a":1}');
if (result instanceof Error) {
console.error('Parse failed:', result);
} else {
console.log('Parsed:', result);
}
// โ
Recommended approach (try/catch)
try {
const result = JSON.parse('{"a":1}');
console.log('Parsed:', result);
} catch (error) {
console.error('Parse failed:', error);
}
// โ
Recommended approach (Zygos Result)
import { tryCatch } from '@pithos/zygos';
const result = tryCatch(() => JSON.parse('{"a":1}'));
if (result.isOk()) {
console.log('Parsed:', result.value);
} else {
console.error('Parse failed:', result.error);
}
How it works?โ
Attempts to invoke func, returning either the result or the error. Deprecated: Use try-catch directly.
Native Equivalentโ
// โ attempt(fn)
// โ
try { fn() } catch (e) { return e }
Use Casesโ
Safe function call ๐โ
Handle errors gracefully.
try {
return JSON.parse(str);
} catch {
return undefined;
}
Wrap risky operationโ
Provide fallback on error.
const safeJSON = (str) => {
try { return JSON.parse(str); }
catch { return null; }
};
Optional chain alternativeโ
Use try-catch for risky access.
try {
return obj.deeply.nested.value;
} catch {
return defaultValue;
}
Parse JSON safely from untrusted sourcesโ
Parse JSON from localStorage, cookies, or API responses without crashing. The most common real-world use case for attempt โ handling malformed data gracefully.
const raw = localStorage.getItem("user-preferences");
const preferences = attempt(() => JSON.parse(raw ?? ""));
// Returns parsed object if valid JSON, or Error instance if malformed
const safePrefs = isError(preferences)
? { theme: "light", language: "en" }
: preferences;