CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nice-try

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

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/

nice-try

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.

Package Information

  • Package Name: nice-try
  • Package Type: npm
  • Language: JavaScript (ES Modules)
  • Installation: npm install nice-try

Core Imports

import niceTry from 'nice-try';

For the promises variant:

import niceTry from 'nice-try/promises';

Basic Usage

import niceTry from 'nice-try';

// Safe JSON parsing - returns parsed value or undefined
const result = niceTry(() => JSON.parse('{"valid": true}'));
console.log(result); // { valid: true }

// Invalid JSON - returns undefined instead of throwing
const invalid = niceTry(() => JSON.parse('invalid json'));
console.log(invalid); // undefined

// Works with any function that might throw
const safeOperation = niceTry(() => {
  // Some operation that might fail
  return someRiskyFunction();
});

For asynchronous operations:

import niceTry from 'nice-try/promises';

// Safe async operations
const asyncResult = await niceTry(async () => {
  const response = await fetch('/api/data');
  return response.json();
});

// Returns undefined if the fetch or parsing fails
console.log(asyncResult); // parsed data or undefined

Architecture

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

  • Main Entry Point (nice-try): Synchronous function that catches errors in regular functions
  • Promises Entry Point (nice-try/promises): Asynchronous function that catches errors in async functions and promise rejections
  • Unified Interface: Both variants have identical function signatures and behavior patterns
  • Error Suppression Pattern: Complete error silencing - all exceptions become undefined returns
  • Input Validation: Both variants handle non-function inputs gracefully by returning undefined

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.

Capabilities

Synchronous Error Suppression

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

/**
 * Executes the provided function and returns its result.
 * If an error is thrown during execution, the error is silently ignored and undefined is returned.
 * 
 * @param {Function} fn - The function to execute.
 * @returns {*} The return value of the function, or undefined if an error occurred.
 */
export default function niceTry(fn);

Usage Examples:

import niceTry from 'nice-try';

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

// Property access that might fail
const value = niceTry(() => obj.deeply.nested.property);

// Function call that might throw
const result = niceTry(() => riskyFunction());

// Invalid input handling
const invalid = niceTry(); // undefined (no function provided)
const alsoInvalid = niceTry(42); // undefined (non-function provided)

Asynchronous Error Suppression

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

/**
 * Executes an asynchronous function and returns its result, suppressing any errors that occur.
 * 
 * @param {Function} fn - An asynchronous function to execute.
 * @returns {Promise<any>} The result of the function if it resolves successfully, otherwise undefined if an error is thrown.
 */
export default async function niceTry(fn);

Usage Examples:

import niceTry from 'nice-try/promises';

// Safe API calls
const apiData = await niceTry(async () => {
  const response = await fetch('/api/endpoint');
  return response.json();
});

// Safe file operations (in Node.js)
const fileContent = await niceTry(async () => {
  const fs = await import('fs/promises');
  return fs.readFile('config.json', 'utf8');
});

// Safe database operations
const user = await niceTry(async () => {
  return await db.user.findById(userId);
});

Error Handling

Both variants of niceTry provide complete error suppression:

  • All exceptions are caught: Any error thrown by the provided function is silently caught
  • No error propagation: Errors never bubble up to the caller
  • Consistent return value: Always returns undefined when an error occurs
  • Input validation: Non-function inputs are handled gracefully by returning undefined

Use Cases

Common scenarios where nice-try is useful:

  • Optional JSON parsing: Parse JSON that might be malformed without crashing
  • Safe property access: Access object properties that might not exist
  • Graceful degradation: Attempt operations that might fail in certain environments
  • Configuration loading: Load optional configuration files without errors
  • API calls: Make network requests that might fail without interrupting flow
  • Feature detection: Test for browser/environment capabilities safely

docs

index.md

tile.json