or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-nice-try

A function that tries to execute a function and discards any error that occurs

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/nice-try@4.0.x

To install, run

npx @tessl/cli install tessl/npm-nice-try@4.0.0

0

# nice-try

1

2

A utility function that tries to execute a function and discards any error that occurs, returning undefined instead of throwing. The package provides both synchronous and asynchronous variants for safe error suppression in JavaScript applications.

3

4

## Package Information

5

6

- **Package Name**: nice-try

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES Modules)

9

- **Installation**: `npm install nice-try`

10

11

## Core Imports

12

13

```javascript

14

import niceTry from 'nice-try';

15

```

16

17

For the promises variant:

18

19

```javascript

20

import niceTry from 'nice-try/promises';

21

```

22

23

## Basic Usage

24

25

```javascript

26

import niceTry from 'nice-try';

27

28

// Safe JSON parsing - returns parsed value or undefined

29

const result = niceTry(() => JSON.parse('{"valid": true}'));

30

console.log(result); // { valid: true }

31

32

// Invalid JSON - returns undefined instead of throwing

33

const invalid = niceTry(() => JSON.parse('invalid json'));

34

console.log(invalid); // undefined

35

36

// Works with any function that might throw

37

const safeOperation = niceTry(() => {

38

// Some operation that might fail

39

return someRiskyFunction();

40

});

41

```

42

43

For asynchronous operations:

44

45

```javascript

46

import niceTry from 'nice-try/promises';

47

48

// Safe async operations

49

const asyncResult = await niceTry(async () => {

50

const response = await fetch('/api/data');

51

return response.json();

52

});

53

54

// Returns undefined if the fetch or parsing fails

55

console.log(asyncResult); // parsed data or undefined

56

```

57

58

## Architecture

59

60

nice-try is built around a dual-entry pattern providing both synchronous and asynchronous error suppression:

61

62

- **Main Entry Point** (`nice-try`): Synchronous function that catches errors in regular functions

63

- **Promises Entry Point** (`nice-try/promises`): Asynchronous function that catches errors in async functions and promise rejections

64

- **Unified Interface**: Both variants have identical function signatures and behavior patterns

65

- **Error Suppression Pattern**: Complete error silencing - all exceptions become `undefined` returns

66

- **Input Validation**: Both variants handle non-function inputs gracefully by returning `undefined`

67

68

This design allows developers to choose the appropriate variant based on whether they're working with synchronous or asynchronous operations while maintaining a consistent API experience.

69

70

## Capabilities

71

72

### Synchronous Error Suppression

73

74

Executes a synchronous function and silently catches any errors that occur.

75

76

```javascript { .api }

77

/**

78

* Executes the provided function and returns its result.

79

* If an error is thrown during execution, the error is silently ignored and undefined is returned.

80

*

81

* @param {Function} fn - The function to execute.

82

* @returns {*} The return value of the function, or undefined if an error occurred.

83

*/

84

export default function niceTry(fn);

85

```

86

87

**Usage Examples:**

88

89

```javascript

90

import niceTry from 'nice-try';

91

92

// JSON parsing

93

const data = niceTry(() => JSON.parse(jsonString));

94

95

// Property access that might fail

96

const value = niceTry(() => obj.deeply.nested.property);

97

98

// Function call that might throw

99

const result = niceTry(() => riskyFunction());

100

101

// Invalid input handling

102

const invalid = niceTry(); // undefined (no function provided)

103

const alsoInvalid = niceTry(42); // undefined (non-function provided)

104

```

105

106

### Asynchronous Error Suppression

107

108

Executes an asynchronous function and silently catches any errors that occur.

109

110

```javascript { .api }

111

/**

112

* Executes an asynchronous function and returns its result, suppressing any errors that occur.

113

*

114

* @param {Function} fn - An asynchronous function to execute.

115

* @returns {Promise<any>} The result of the function if it resolves successfully, otherwise undefined if an error is thrown.

116

*/

117

export default async function niceTry(fn);

118

```

119

120

**Usage Examples:**

121

122

```javascript

123

import niceTry from 'nice-try/promises';

124

125

// Safe API calls

126

const apiData = await niceTry(async () => {

127

const response = await fetch('/api/endpoint');

128

return response.json();

129

});

130

131

// Safe file operations (in Node.js)

132

const fileContent = await niceTry(async () => {

133

const fs = await import('fs/promises');

134

return fs.readFile('config.json', 'utf8');

135

});

136

137

// Safe database operations

138

const user = await niceTry(async () => {

139

return await db.user.findById(userId);

140

});

141

```

142

143

## Error Handling

144

145

Both variants of `niceTry` provide complete error suppression:

146

147

- **All exceptions are caught**: Any error thrown by the provided function is silently caught

148

- **No error propagation**: Errors never bubble up to the caller

149

- **Consistent return value**: Always returns `undefined` when an error occurs

150

- **Input validation**: Non-function inputs are handled gracefully by returning `undefined`

151

152

## Use Cases

153

154

Common scenarios where `nice-try` is useful:

155

156

- **Optional JSON parsing**: Parse JSON that might be malformed without crashing

157

- **Safe property access**: Access object properties that might not exist

158

- **Graceful degradation**: Attempt operations that might fail in certain environments

159

- **Configuration loading**: Load optional configuration files without errors

160

- **API calls**: Make network requests that might fail without interrupting flow

161

- **Feature detection**: Test for browser/environment capabilities safely