Tries to execute a function and discards any error that occurs
Nice Try is a minimal JavaScript utility library that provides safe function execution with automatic error handling. It offers two main functions: a synchronous version that wraps function calls in try-catch blocks and returns undefined on errors, and an asynchronous version that handles promise-based functions similarly.
npm install nice-tryconst niceTry = require('nice-try');Nice Try uses a simple wrapper pattern around JavaScript's try-catch mechanism:
undefined on any errorundefinedundefined on error (never null or other falsy values)This pattern is useful for scenarios where you want to attempt an operation but continue execution regardless of whether it succeeds or fails.
const niceTry = require('nice-try');
// Synchronous function execution - returns result or undefined
const result = niceTry(() => JSON.parse('{"valid": true}'));
console.log(result); // { valid: true }
const failed = niceTry(() => JSON.parse('invalid json'));
console.log(failed); // undefined
// Asynchronous function execution
const asyncResult = await niceTry.promise(async () => {
const response = await fetch('/api/data');
return response.json();
});
console.log(asyncResult); // API response or undefined if failedExecutes a function and returns its result, or undefined if an error occurs.
/**
* Tries to execute a function and discards any error that occurs.
* @param {Function} fn - Function that might or might not throw an error.
* @returns {?*} Return-value of the function when no error occurred, undefined otherwise.
*/
niceTry(fn);Usage Examples:
const niceTry = require('nice-try');
// JSON parsing that might fail
const data = niceTry(() => JSON.parse(userInput));
if (data) {
console.log('Valid JSON:', data);
} else {
console.log('Invalid JSON, using defaults');
}
// File system operations that might fail
const config = niceTry(() => require('./config.json')) || {};
// Function calls that might throw
const result = niceTry(() => riskyOperation()) || fallbackValue;
// Works with any synchronous operation
const parsed = niceTry(() => new URL(userUrl));
const number = niceTry(() => parseInt(userInput, 10));Executes an asynchronous function and returns a promise that resolves to the result, or undefined if an error occurs.
/**
* Tries to execute an asynchronous function and discards any error that occurs.
* @param {Function} fn - Asynchronous function that might or might not throw an error.
* @returns {Promise<?*>} Promise which resolves with the return-value of the asynchronous function when no error occurred, undefined otherwise.
*/
niceTry.promise(fn);Usage Examples:
const niceTry = require('nice-try');
// API calls that might fail
const userData = await niceTry.promise(async () => {
const response = await fetch('/api/user');
return response.json();
});
if (userData) {
console.log('User data:', userData);
} else {
console.log('Failed to fetch user data');
}
// File operations that might fail
const fileContent = await niceTry.promise(async () => {
const fs = require('fs').promises;
return await fs.readFile('data.txt', 'utf8');
});
// Database operations
const records = await niceTry.promise(async () => {
return await database.query('SELECT * FROM users');
});
// Any async operation that might throw
const result = await niceTry.promise(async () => {
return await someAsyncOperation();
}) || defaultValue;Both functions use try-catch blocks internally to catch any errors that occur during function execution. All errors are silently discarded, and the functions return undefined when an error occurs.
Error scenarios that return undefined:
When to Use:
When NOT to Use:
Important Notes:
undefined on error (not null or other falsy values)