attempt
util
Attempts to invoke func, returning either the result or the caught error object.
Installation
Import
import { attempt } from '@tulx/utils';Source Code
Implementation
/**
* Attempts to invoke func, returning either the result or the caught error object.
*
* @param func - The function to attempt.
* @param args - The arguments to invoke func with.
* @returns Returns the func result or error object.
*
* @example
* ```ts
* const elements = attempt((selector: string) => document.querySelectorAll(selector), '>_>');
* if (isError(elements)) {
* elements = [];
* }
* ```
*/
export function attempt<T extends (...args: unknown[]) => unknown>(
func: T,
...args: Parameters<T>
): ReturnType<T> | Error {
try {
return func(...args) as ReturnType<T>;
} catch (error) {
return error instanceof Error ? error : new Error(String(error));
}
}
Example
import { attempt } from '@tulx/utils';
const elements = attempt((selector: string) => document.querySelectorAll(selector), '>_>');
if (isError(elements)) {
elements = [];
}Related Functions
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
cond
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.
flow
Creates a function that returns the result of invoking the given functions with the this binding of the created function.