• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How To Handle Async/Await Errors in Javascript

Javascript · August 24, 2020

Some developers are still new to async/await in Javascript. If you’re used to callbacks or using .then to get the value of a promise, async/await can be a bit of a black box, especially when it comes to errors.

The most straightforward and recommended way to handle errors is using try/catch. This will allow you to catch errors if your async function rejects or throws an error.

async function getProducts() {
  try {
    const response = await fetch('/products');
    const products = await response.json();
  } catch(err) {
    console.error(err);
  }
}

If you had a function which handles API requests, you could do something like this:

async function request(endpoint) {
    const response = await fetch(endpoint);
    return response.json();
}

async function getProducts() {
  try {
      const products = await request('/products);
  } catch (err) {
    console.error(err);
  }
}

You can even make the request method shorter by doing this:

async function request(endpoint) {
	return (await fetch(endpoint)).json();
}

My preference when working with promises is to always use async/await and break my logic for fetching content into separate functions. I tend to exclusively work with native Fetch these days and find breaking up my code makes it easier to work with.

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • Thoughts on the Flipper Zero
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • Reliably waiting for network responses in Playwright
  • How To Mock uuid In Jest
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Wild Natural Deodorant Review

Recent Comments

  • Dwayne on Is Asking Developers How to Write FizzBuzz Outdated?
  • kevmeister68 on Is Asking Developers How to Write FizzBuzz Outdated?
  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz