The lodash method _.attempt exported as a module for safe function execution with error handling
npx @tessl/cli install tessl/npm-lodash--attempt@4.2.0lodash.attempt provides the lodash _.attempt method as a standalone modular Node.js package. The attempt function executes a given function and returns either its result or any error that was thrown during execution, enabling safe execution of potentially failing operations without throwing unhandled exceptions.
npm install lodash.attemptconst attempt = require('lodash.attempt');For ES modules:
import attempt from 'lodash.attempt';const attempt = require('lodash.attempt');
// Avoid throwing errors for invalid selectors
const elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) {
console.log('Invalid selector, using empty array');
elements = [];
}
// Safe JSON parsing
const result = attempt(JSON.parse, '{"invalid": json}');
if (result instanceof Error) {
console.log('Invalid JSON:', result.message);
} else {
console.log('Parsed:', result);
}Attempts to invoke a function, returning either the result or the caught error object.
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
*/
function attempt(func, ...args);Parameters:
func (Function): The function to attempt to invoke...args (any[]): Optional additional arguments provided to func when invokedReturns:
func if successful, or an Error object if an exception was thrownError Handling:
func throws an object (including Error instances), returns that object unchangedfunc throws a primitive value (string, number, etc.), wraps it in a new Error instanceUsage Examples:
const attempt = require('lodash.attempt');
// Basic usage with successful execution
const result = attempt(() => 2 + 2);
console.log(result); // 4
// Function that throws an error
const errorResult = attempt(() => {
throw new Error('Something went wrong');
});
console.log(errorResult instanceof Error); // true
console.log(errorResult.message); // 'Something went wrong'
// Function that throws a string
const stringError = attempt(() => {
throw 'Custom error message';
});
console.log(stringError instanceof Error); // true
console.log(stringError.message); // 'Custom error message'
// Passing arguments to the attempted function
const mathResult = attempt((a, b) => a / b, 10, 2);
console.log(mathResult); // 5
const divisionError = attempt((a, b) => {
if (b === 0) throw new Error('Division by zero');
return a / b;
}, 10, 0);
console.log(divisionError instanceof Error); // true
// Real-world example: Safe DOM querying
const safeQuery = (selector) => {
const result = attempt(document.querySelectorAll.bind(document), selector);
return result instanceof Error ? [] : Array.from(result);
};
const elements = safeQuery('div'); // Works fine
const invalidElements = safeQuery('>>>invalid'); // Returns empty array instead of throwing