globalThis.assertOrThrow

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

globalThis.assertOrThrow

kai zhu
having a universal assert function (similar to nodejs' assert builtin) might be useful.  it could be name "assertOrThrow" for web-compat.

this would simplify writing common-case "throwaway" error-handling behavior in both browsers and nodejs:

```js
// naive polyfill
globalThis.assertOrThrow = globalThis.assertOrThrow || function (passed, message) {
/*
 * this function will throw error <message> if <passed> is falsy
 */
    if (passed) {
        return;
    }
    throw (
        typeof message === "object" && message
        ? message
        : new Error(message)
    }
};

localforage.setItem("foo", "bar", function (err, data) {
    // validate no err occurred
    // this one-line statement makes writing test-coverage less tedious
    assertOrThrow(!err, err);
    ...
});
```

-kai


_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

RE: globalThis.assertOrThrow

Michael Haufe-2

https://esdiscuss.org/topic/native-assertions

 

From: es-discuss <[hidden email]> On Behalf Of kai zhu
Sent: Saturday, August 31, 2019 2:22 PM
To: es-discuss <[hidden email]>
Subject: globalThis.assertOrThrow

 

having a universal assert function (similar to nodejs' assert builtin) might be useful.  it could be name "assertOrThrow" for web-compat.

 

this would simplify writing common-case "throwaway" error-handling behavior in both browsers and nodejs:

 

```js

// naive polyfill

globalThis.assertOrThrow = globalThis.assertOrThrow || function (passed, message) {

/*
 * this function will throw error <message> if <passed> is falsy
 */

    if (passed) {

        return;

    }

    throw (

        typeof message === "object" && message

        ? message

        : new Error(message)

    }

};

 

localforage.setItem("foo", "bar", function (err, data) {

    // validate no err occurred

    // this one-line statement makes writing test-coverage less tedious

    assertOrThrow(!err, err);

    ...

});

```

 

-kai

 


_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss