try/catch blocks with async/await

node.jsAsync AwaitEcmascript 2017

node.js Problem Overview


I'm digging into the node 7 async/await feature and keep stumbling across code like this

function getQuote() {
  let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit laborum.";
  return quote;
}

async function main() {
  try {
    var quote = await getQuote();
    console.log(quote);
  } catch (error) {
    console.error(error);
  }
}

main();

This seems to be the only possibility resolve/reject or return/throw with async/await, however, v8 doesn't optimise code within try/catch blocks?!

Are there alternatives?

node.js Solutions


Solution 1 - node.js

Alternatives

An alternative to this:

async function main() {
  try {
    var quote = await getQuote();
    console.log(quote);
  } catch (error) {
    console.error(error);
  }
}

would be something like this, using promises explicitly:

function main() {
  getQuote().then((quote) => {
    console.log(quote);
  }).catch((error) => {
    console.error(error);
  });
}

or something like this, using continuation passing style:

function main() {
  getQuote((error, quote) => {
    if (error) {
      console.error(error);
    } else {
      console.log(quote);
    }
  });
}

Original example

What your original code does is suspend the execution and wait for the promise returned by getQuote() to settle. It then continues the execution and writes the returned value to var quote and then prints it if the promise was resolved, or throws an exception and runs the catch block that prints the error if the promise was rejected.

You can do the same thing using the Promise API directly like in the second example.

Performance

Now, for the performance. Let's test it!

I just wrote this code - f1() gives 1 as a return value, f2() throws 1 as an exception:

function f1() {
  return 1;
}

function f2() {
  throw 1;
}

Now let's call the same code million times, first with f1():

var sum = 0;
for (var i = 0; i < 1e6; i++) {
  try {
    sum += f1();
  } catch (e) {
    sum += e;
  }
}
console.log(sum);

And then let's change f1() to f2():

var sum = 0;
for (var i = 0; i < 1e6; i++) {
  try {
    sum += f2();
  } catch (e) {
    sum += e;
  }
}
console.log(sum);

This is the result I got for f1:

$ time node throw-test.js 
1000000

real    0m0.073s
user    0m0.070s
sys     0m0.004s

This is what I got for f2:

$ time node throw-test.js 
1000000

real    0m0.632s
user    0m0.629s
sys     0m0.004s

It seems that you can do something like 2 million throws a second in one single-threaded process. If you're doing more than that then you may need to worry about it.

Summary

I wouldn't worry about things like that in Node. If things like that get used a lot then it will get optimized eventually by the V8 or SpiderMonkey or Chakra teams and everyone will follow - it's not like it's not optimized as a principle, it's just not a problem.

Even if it isn't optimized then I'd still argue that if you're maxing out your CPU in Node then you should probably write your number crunching in C - that's what the native addons are for, among other things. Or maybe things like node.native would be better suited for the job than Node.js.

I'm wondering what would be a use case that needs throwing so many exceptions. Usually throwing an exception instead of returning a value is, well, an exception.

Solution 2 - node.js

Alternative Similar To Error Handling In Golang

Because async/await uses promises under the hood, you can write a little utility function like this:

export function catchEm(promise) {
  return promise.then(data => [null, data])
    .catch(err => [err]);
}

Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.

import catchEm from 'utility';

async performAsyncWork() {
  const [err, data] = await catchEm(asyncFunction(arg1, arg2));
  if (err) {
    // handle errors
  } else {
    // use data
  }
}

Solution 3 - node.js

An alternative to try-catch block is await-to-js lib. I often use it. For example:

import to from 'await-to-js';

async function main(callback) {
    const [err,quote] = await to(getQuote());
    
    if(err || !quote) return callback(new Error('No Quote found'));

    callback(null,quote);

}

This syntax is much cleaner when compared to try-catch.

Solution 4 - node.js

async function main() {
  var getQuoteError
  var quote = await getQuote().catch(err => { getQuoteError = err }

  if (getQuoteError) return console.error(err)

  console.log(quote)
}

Alternatively instead of declaring a possible var to hold an error at the top you can do

if (quote instanceof Error) {
  // ...
}

Though that won't work if something like a TypeError or Reference error is thrown. You can ensure it is a regular error though with

async function main() {
  var quote = await getQuote().catch(err => {
    console.error(err)      

    return new Error('Error getting quote')
  })

  if (quote instanceOf Error) return quote // get out of here or do whatever

  console.log(quote)
}

My preference for this is wrapping everything in a big try-catch block where there's multiple promises being created can make it cumbersome to handle the error specifically to the promise that created it. With the alternative being multiple try-catch blocks which I find equally cumbersome

Solution 5 - node.js

A cleaner alternative would be the following:

Due to the fact that every async function is technically a promise

You can add catches to functions when calling them with await

async function a(){
    let error;

    // log the error on the parent
    await b().catch((err)=>console.log('b.failed'))

    // change an error variable
    await c().catch((err)=>{error=true; console.log(err)})

    // return whatever you want
    return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.

Solution 6 - node.js

I think, a simple and well explained example is from How to use promises of MDN DOCS.

As an example they use the API Fetch then 2 types, one normal and the other an hybrid where the async and Promise are mixed together.

  1. Simple Example
async function myFetch() {
  let response = await fetch("coffee.jpg");
  // Added manually a validation and throws an error
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  let myBlob = await response.blob();

  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement("img");
  image.src = objectURL;
  document.body.appendChild(image);
}

myFetch().catch((e) => {
  // Catches the errors...
  console.log("There has been a problem with your fetch operation: " + e.message);
});

  1. Hybrid approach

> Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible:

async function myFetch() {
  // Uses async
  let response = await fetch("coffee.jpg");
  // Added manually a validation and throws an error
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.blob();
}

myFetch()
  .then((blob) => {
    // uses plain promise
    let objectURL = URL.createObjectURL(blob);
    let image = document.createElement("img");
    image.src = objectURL;
    document.body.appendChild(image);
  })
  .catch((e) => console.log(e));

Adding error handling

  1. Normal
async function myFetch() {
  try {
    let response = await fetch("coffee.jpg");

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    let myBlob = await response.blob();
    let objectURL = URL.createObjectURL(myBlob);
    let image = document.createElement("img");
    image.src = objectURL;
    document.body.appendChild(image);
  } catch (e) {
    console.log(e);
  }
}

myFetch();

  1. Hybrid (Best)
async function myFetch() {
  let response = await fetch("coffee.jpg");
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.blob();
}

myFetch()
  .then((blob) => {
    let objectURL = URL.createObjectURL(blob);
    let image = document.createElement("img");
    image.src = objectURL;
    document.body.appendChild(image);
  })
  .catch(
    (
      e // Not need a try catch. This will catch it all already!
    ) => console.log(e)
  );

Best solution

The best solution given, which follow these principle but adds more clarity is this answer --> StackOverflow: try/catch blocks with async/await I believe. Here

function promiseHandle(promise) {
  return promise.then((data) => [null, data]).catch((err) => [err]);
}

async function asyncFunc(param1, param2) {
  const [err, data] = await promiseHandle(expensiveFunction(param1, param2));
  // This just to show, that in this way we can control what is going on..
  if (err || !data) {
    if (err) return Promise.reject(`Error but not data..`);
    return Promise.reject(`Error but not data..`);
  }
  return Promise.resolve(data);
}

Solution 7 - node.js

I'd like to do this way :)

const sthError = () => Promise.reject('sth error');

const test = opts => {
  return (async () => {

    // do sth
    await sthError();
    return 'ok';

  })().catch(err => {
    console.error(err); // error will be catched there 
  });
};

test().then(ret => {
  console.log(ret);
});

It's similar to handling error with co

const test = opts => {
  return co(function*() {

    // do sth
    yield sthError();
    return 'ok';

  }).catch(err => {
    console.error(err);
  });
};

Solution 8 - node.js

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
  apiClient.getCurrentUser()
);

Solution 9 - node.js

No need for a library like await-to-js, a simple one-liner for the to-function (also shown in other answers) will do:

const to = promise => promise.then(res => [null, res]).catch(err => [err || true, null]);

Usage:

async function main()
{
    var [err, quote] = await to(getQuote());
    if(err)
    {
        console.log('warn: Could not get quote.');
    }
    else
    {
        console.log(quote);
    }
}

However, if the error leads to termination of the function or program, such as:

async function main()
{
    var [err, quote] = await to(getQuote());
    if(err) return console.error(err);
    console.log(quote);
}

Then you might as well simply let the error return from main() automatically, which is the intended purpose of an exception anyway:

async function main()
{
    var quote = await getQuote();
    console.log(quote);
}

main().catch(err => console.error('error in main():', err));

Throwing an error vs returning an error

If you are expected to deal with an error that is expected to occur, then using throw or reject is bad practice. Instead, let the getQuote() function always resolve using any of these:

  • resolve([err, result])
  • resolve(null)
  • resolve(new Error(...))
  • resolve({error: new Error(), result: null})
  • etc.

Throwing an error (or the equivalent in async: rejecting a promise) must remain an exception. Since an exception only happens when things go south, and should not happen during normal usage, optimization is therefore not a priority. Thus, the only consequence of an exception, can be termination of the function, which is the default behavior if not caught anyway.

Unless you deal with badly designed 3rd-party libraries, or you are using a 3rd-party library function for an unintended use-case, you should probably not be using the to-function.

Solution 10 - node.js

In case of Express framework, I generally follow the following method. We can create a function which resolves a promise. Like the catchAsync function:

const catchAsync = (fn) => (req, res, next) =>{
    Promise.resolve(fn(req, res, next)).catch((err) => next(err));
});

This function can be called wherever we require try/catch.It takes in the function which we call and resolves or rejects it based on the action being carried. Here's how we can call it

const sampleFunction = catchAsync(async (req, res) => {
           const awaitedResponse = await getResponse();
           res.send(awaitedResponse);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickView Question on Stackoverflow
Solution 1 - node.jsrspView Answer on Stackoverflow
Solution 2 - node.jsSteve BantonView Answer on Stackoverflow
Solution 3 - node.jsPulkit chadhaView Answer on Stackoverflow
Solution 4 - node.jsTonyView Answer on Stackoverflow
Solution 5 - node.jszardiliorView Answer on Stackoverflow
Solution 6 - node.jsFederico BaùView Answer on Stackoverflow
Solution 7 - node.jsCooper HsiungView Answer on Stackoverflow
Solution 8 - node.jsKabir SarinView Answer on Stackoverflow
Solution 9 - node.jsYetiView Answer on Stackoverflow
Solution 10 - node.jsmr.meeseeksView Answer on Stackoverflow