πŸ’‘Why use it?

Github Reponpm package

Handling errors is never easy. Let's take a look at 2 cases.

Unexpected Crashes

It's common to import some functions either written by other teammates or from NPM packages.

import {plusOne} from 'lib'
// plusOne(a: number) => number

function handler() {
    const ret = plusOne(1)
    console.log(ret)
}

This handler function is so simple, yet it still has a chance to cause the program to crash.

How come? Well, based on the signature of plusOne we can't find any clue. If we look into the implementation of plusOne you'll find that it will throw an error when the given number is even.

function plusOne(a: number) {
    if (a % 2 === 0) throw new Error('Given number is even.')
    return a + 1
}

Even TypeScript won't give you any hints that the function might throw errors.

You might want to add the return type manually

But the truth is that even if you do this, TypeScript still won't warn you that the code might throw errors. Check the TS Playground.

If you still don't get it, replace plusOne with JSON.parse.

If we don't read the document carefully, or the document just doesn't mention this trivial and we don't test it out during tests as well, tragedy might happen.

Try/Catch

Let's take a look at a more complex example

In this example, we need to get a lot of data from somewhere, and each step relies on the result of the above step, so they are invoked sequentially. We also want to provide fine-grained error message hints and return the function whenever an error occurs.

With these 2 problems in the mind, let take a look at how unwrapit solve this.

Just unwrapit!

The idea of unwrapit is inspired by rust. The concept behind unwrapit is simple. Program crashes because of unexpected errors being thrown out, what if we wrap them up into a box, and then let users unwrap them?

Let's take a look at how to improve the above 2 cases by using unwrapit

case 1: unexpected crashed

case 2: try/catch

For more usages, just head to Recipe section!

Last updated