CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lodash-attempt

The lodash method _.attempt exported as a module for safe function execution with error handling

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

lodash.attempt

lodash.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.

Package Information

  • Package Name: lodash.attempt
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash.attempt

Core Imports

const attempt = require('lodash.attempt');

For ES modules:

import attempt from 'lodash.attempt';

Basic Usage

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);
}

Capabilities

Safe Function Execution

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 invoked

Returns:

  • (any | Error): Returns the result of func if successful, or an Error object if an exception was thrown

Error Handling:

  • If func throws an object (including Error instances), returns that object unchanged
  • If func throws a primitive value (string, number, etc.), wraps it in a new Error instance
  • Never throws exceptions - all errors are returned as values

Usage 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

docs

index.md

tile.json