on-error-resume-next

1.1.0 • Public • Published

on-error-resume-next

Run a function, synchronously or asynchronously, and ignore errors.

npm version Build Status

The name come from Visual Basic. The original On Error Resume Next statement is considered a bad error handling practice.

Although the perception of the feature is negative, when scoped and used responsibly, it can become a very helpful utility function.

Usage

onErrorResumeNext will return the result if it is a success. For example,

import onErrorResumeNext from 'on-error-resume-next';
 
const text = '{"hello":"World!"}';
const parsed = onErrorResumeNext(() => JSON.parse(text));
 
expect(parsed).toEqual({ hello: 'World!' });

Otherwise, it will return undefined,

const parsed = onErrorResumeNext(() => JSON.parse('<xml />'));
 
expect(parsed).toBeUndefined();

When using onErrorResumeNext, please be responsible and fully understand the impact of ignoring errors.

Asynchronous using async/await

onErrorResumeNext will capture both exceptions (synchronous) and rejections (asynchronous). It is recommended to pair up with await keyword to handle both cases in the same way.

const res = await onErrorResumeNext(() => fetch('/health'));
 
expect(res).toBeUndefined();

The code is for elaboration only, the better expectation should be expect(res).resolves.toBeUndefined().

Contributions

Like us? Star us.

Want to make it better? File us an issue.

Don't like something you see? Submit a pull request.

Readme

Keywords

none

Package Sidebar

Install

npm i on-error-resume-next

Weekly Downloads

7,833

Version

1.1.0

License

MIT

Unpacked Size

9.59 kB

Total Files

9

Last publish

Collaborators

  • compulim