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.00
# lodash.attempt
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: lodash.attempt
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.attempt`
10
11
## Core Imports
12
13
```javascript
14
const attempt = require('lodash.attempt');
15
```
16
17
For ES modules:
18
19
```javascript
20
import attempt from 'lodash.attempt';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const attempt = require('lodash.attempt');
27
28
// Avoid throwing errors for invalid selectors
29
const elements = attempt(function(selector) {
30
return document.querySelectorAll(selector);
31
}, '>_>');
32
33
if (elements instanceof Error) {
34
console.log('Invalid selector, using empty array');
35
elements = [];
36
}
37
38
// Safe JSON parsing
39
const result = attempt(JSON.parse, '{"invalid": json}');
40
if (result instanceof Error) {
41
console.log('Invalid JSON:', result.message);
42
} else {
43
console.log('Parsed:', result);
44
}
45
```
46
47
## Capabilities
48
49
### Safe Function Execution
50
51
Attempts to invoke a function, returning either the result or the caught error object.
52
53
```javascript { .api }
54
/**
55
* Attempts to invoke `func`, returning either the result or the caught error
56
* object. Any additional arguments are provided to `func` when it's invoked.
57
*
58
* @param {Function} func The function to attempt.
59
* @param {...*} [args] The arguments to invoke `func` with.
60
* @returns {*} Returns the `func` result or error object.
61
*/
62
function attempt(func, ...args);
63
```
64
65
**Parameters:**
66
- `func` (Function): The function to attempt to invoke
67
- `...args` (any[]): Optional additional arguments provided to `func` when invoked
68
69
**Returns:**
70
- (any | Error): Returns the result of `func` if successful, or an Error object if an exception was thrown
71
72
**Error Handling:**
73
- If `func` throws an object (including Error instances), returns that object unchanged
74
- If `func` throws a primitive value (string, number, etc.), wraps it in a new Error instance
75
- Never throws exceptions - all errors are returned as values
76
77
**Usage Examples:**
78
79
```javascript
80
const attempt = require('lodash.attempt');
81
82
// Basic usage with successful execution
83
const result = attempt(() => 2 + 2);
84
console.log(result); // 4
85
86
// Function that throws an error
87
const errorResult = attempt(() => {
88
throw new Error('Something went wrong');
89
});
90
console.log(errorResult instanceof Error); // true
91
console.log(errorResult.message); // 'Something went wrong'
92
93
// Function that throws a string
94
const stringError = attempt(() => {
95
throw 'Custom error message';
96
});
97
console.log(stringError instanceof Error); // true
98
console.log(stringError.message); // 'Custom error message'
99
100
// Passing arguments to the attempted function
101
const mathResult = attempt((a, b) => a / b, 10, 2);
102
console.log(mathResult); // 5
103
104
const divisionError = attempt((a, b) => {
105
if (b === 0) throw new Error('Division by zero');
106
return a / b;
107
}, 10, 0);
108
console.log(divisionError instanceof Error); // true
109
110
// Real-world example: Safe DOM querying
111
const safeQuery = (selector) => {
112
const result = attempt(document.querySelectorAll.bind(document), selector);
113
return result instanceof Error ? [] : Array.from(result);
114
};
115
116
const elements = safeQuery('div'); // Works fine
117
const invalidElements = safeQuery('>>>invalid'); // Returns empty array instead of throwing
118
```