Skip to content

An elegant try-catch replacement for JavaScript / TypeScript

License

Notifications You must be signed in to change notification settings

jeeyo/safely-try

Repository files navigation

safely-try

Test npm

safelyTry() is an elegant try-catch replacement for JavaScript / TypeScript inspired by Go error handling

Installation

npm i --save safely-try

Usage

Instead of using ugly native try-catch like this

let result;
try {
  result = somethingMightThrowException();
} catch(e) {
  handleTheError(e);
}

you can use safelyTry to do something like this

import safelyTry from 'safely-try';

const { data: result, error } = safelyTry(somethingMightThrowException);
if (error) {
  handleTheError(error);
  return;
}

// synchronous functions
safelyTry(() => 1) === { data: 1, error: undefined }
safelyTry((x, y) => x + y, 1, 2) === { data: 3, error: undefined }
safelyTry(() => { throw '1' }) === { data: undefined, error: '1' }
safelyTry(() => { throw new Error('1') }) === { data: undefined, error: Error('1') }

// asynchronous functions
await safelyTry(async () => Promise.resolve(1)) === { data: 1, error: undefined }
await safelyTry(async (x, y) => Promise.resolve(x + y), 1, 2) === { data: 3, error: undefined }
await safelyTry(async () => Promise.reject('1')) === { data: undefined, error: '1' }
await safelyTry(async () => Promise.reject(new Error('1'))) === { data: undefined, error: Error('1') }

About

An elegant try-catch replacement for JavaScript / TypeScript

Resources

License

Stars

Watchers

Forks

Packages

No packages published