handle-async-await

Graceful Error Handling with Async Await

Usage no npm install needed!

<script type="module">
  import handleAsyncAwait from 'https://cdn.skypack.dev/handle-async-await';
</script>

README

Handle Async Await

The Anti-Pattern

You want to use an async function with an error handler. So you use a try-catch block. But now you cannot assign the return value of this async function to a constant declared outside the try-catch because of the block scope. And so you are forced to use a variable in lieu of a constant!

let x; // not const
try {
  x = await myAsyncFn()
}
catch (error) {
  handleError(error);
}

You can always place the try-catch block in a function but this gets tedious and breaks the flow of program logic:

function myAsyncFnWithErrorHandler() {
  try {
    return await myAsyncFn();
  }
  catch (error) {
    handleError(error);
  }
}

const x = await myAsyncFnWithErrorHandler();

Handle Async Await makes it easier to use async functions with error handling.

Installation

Install Handle Async Await with your favourite package manager:

<npm|pnpm|yarn> add handle-async-await

Usage

Error Handler

In the most general form, users can supply their own error handling function.

import handleAA from 'handle-async-await';

const x = await handleAA(myAsyncFn(), handleError);

Error String

If you just wish to augment the error message and throw an error, supply only the string to be appended to the error message as the second argument.

import handleAA from 'handle-async-await';

const x = await handleAA(myAsyncFn(), 'A custom error message');

A space is added when the error message does not end with a whitespace. Bring your own punctuation!

Copyright & License

Copyright © 2021, Rahul Gupta.

Handle Async Await is distributed under the terms of the Mozilla Public License, v. 2.0.