3.1.3 • Published 1 year ago

multitry v3.1.3

Weekly downloads
-
License
BlueOak-1.0.0
Repository
github
Last release
1 year ago

Multitry

Documentation NPM CodePen

Multitry is a wrapper with a different take on try-catch-finally construction.

If you've ever written try to catch, you've run into variable scope, nested try to catch, or just ignored catch - you can use this wrapper to avoid them!

Install with npm install multitry.

Usage and API

Import

The package is written in TypeScript and compiled in JavaScript ESM, there is no support for CommonJS, keep that in mind!

// Normal import
import { wrap } from "multitry";
// Jsx / Tsx import
import { Wrap } from "multitry";
// Cdn import
import { wrap } from "https://www.unpkg.com/multitry/dist/lib/index.js";

Error handling

One of the main differences of Multitry is that an error will never throw an exception without intervention, the following are examples of how an error or undefined can return, this has positive features because you can handle the error or override the default value immediately.

Ignoring

The error is ignored and the return value can either be a value or undefined. It may be undefined because the error has not been handled.

const result = wrap({
  try: () => JSON.parse("Hello world!"),
});

console.log(result); // "Hello world!"

Error ejection

The returned value can either be a value, an undefined value, or an error object. This happens because catch was specified, but for some reason the error was not handled and returned. Note that the error will return, not throw an exception.

const result = wrap({
  try: () => JSON.parse("Hello world! {"),
  catch: () => undefined,
});

console.error(result); // SyntaxError: Unexpected token H in JSON at position 0...

You can interact with an error in the catch function. Handle the error or just output.

const result = wrap({
  try: () => JSON.parse("Hello world! {"),
  catch: (e) => console.error(e),
}); // SyntaxError: Unexpected token H in JSON at position 0...

Multi

Specifying several tries will return the first successful one. This way you can handle ignoring an error, which is not recommended when you can use catch and is shown just for the example.

const result = wrap({
    // Variable "something" does not exist, which will cause an exception.
    try: () => something
  },
  {
    try: () => "foo",
  }); // foo

Other

JSX / TSX support when you want to render something in the DOM.

<Wrap
  try={() => JSON.parse("Hello world! {")}
  catch={(e) => {
    console.error(e);
    return e.toString();
  }}
/> // SyntaxError: Unexpected token 'H', "Hello world! {" is not valid JSON

Read more about API...

3.1.3

1 year ago

3.1.2

1 year ago

3.1.1

1 year ago

3.1.0

1 year ago

2.3.1

1 year ago

2.3.0

1 year ago

2.2.1

1 year ago

2.2.0

1 year ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.1.0

1 year ago

1.0.0

1 year ago