Aller au contenu principal

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.

DEPRECATED

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

try...catch - MDN


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;