@leismore/unknown2error
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Function unknown2error

Why

try {
    throw anything;
} catch(e) {
    // e = anything
}

In JavaScript, for the variable e, there is no guarantee that e will be an Error object, although e should be an Error object, is generally considered as a best practice. To make it worse, in TypeScript, the e is treated as Unknown type in the strict mode, which enforces developers to write extra conditional statements in every catch block.

This package is designed to provide an elegant solution for this issue.

Installation

npm install @leismore/unknown2error

Test

npm test

Example

import { unknown2error } from '@leismore/unknown2error';

try {
    // ...
}
catch(error) {
    error = unknown2error(error); // error guaranteed to be an Error (or subclass) object
}

API

function unknown2error( error: any ): Error

The function converts anything into an object of Error (or subclasses) class. If error is an object of Error (or subclasses) class, it returns the original error object. With any other type, it will convert it into a string first and then an Error object will be created and returned by using the string as the message parameter.

Copyright

GNU Affero General Public License v3.0

Authors

References

Package Sidebar

Install

npm i @leismore/unknown2error

Weekly Downloads

0

Version

1.0.0

License

AGPL-3.0-only

Unpacked Size

38.6 kB

Total Files

7

Last publish

Collaborators

  • kyle.chine.leismore