CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/npm-nice-try

Tries to execute a function and discards any error that occurs

Overview
Eval results
Files

Nice Try

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.

Package Information

  • Package Name: nice-try
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install nice-try

Core Imports

const niceTry = require('nice-try');

Architecture

Nice Try uses a simple wrapper pattern around JavaScript's try-catch mechanism:

  • Synchronous wrapper: Wraps function calls in try-catch blocks, returning the result on success or undefined on any error
  • Asynchronous wrapper: Wraps async function calls in try-catch blocks, returning a Promise that resolves to the result or undefined
  • Error silencing: All errors are completely discarded - no logging, throwing, or error information is provided
  • Consistent return: Both functions return exactly undefined 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.

Basic Usage

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 failed

Capabilities

Synchronous Error Handling

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

Asynchronous Error Handling

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;

Error Handling

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:

  • Function throws an exception
  • Function is not provided (called with no arguments)
  • Non-function parameter is provided
  • Async function rejects with an error
  • Network failures, parsing errors, etc.

When to Use:

  • Attempting optional operations (like reading config files) where failure is acceptable
  • Parsing user input where invalid input should result in default values
  • Feature detection where method calls might not be supported
  • Quick prototyping where you want to suppress all errors temporarily

When NOT to Use:

  • Critical operations where you need to know if something failed
  • Cases where different error types require different handling
  • Production code where errors should be logged for debugging
  • Operations where partial success/failure states are important

Important Notes:

  • No error information is provided - errors are completely silenced
  • Use only when you want to ignore all possible errors
  • Consider logging or handling errors explicitly for debugging purposes
  • Both functions return exactly undefined on error (not null or other falsy values)
tessl i tessl/npm-nice-try@3.0.0
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/nice-try@3.0.x