Having trouble with catching errors in try/catch using Async/Await in JavaScript?

I've encountered an issue with the JavaScript code snippet below while using async/await in our ES6 project. I've observed that a 404 response code is not triggering the catch block as expected. Moreover, the .json() method is causing a console error but still doesn't redirect to the catch block. It's puzzling because any error in the try block should ideally be caught and handled by the catch block.

async getDash(projectId, projectUserId) {
  try {
    const events = (await this.apiHttp
      .fetch(`${projectId}/users/${projectUserId}/participant-event-dash`)).json();
    return events;
  } catch (e) {
    // fall back to local (dev testing)
    return (await this.http
      .fetch(`${this.appConfig.url}dist/api/query/json/partic-event-dash.json`)).json();
  }
}

Answer №1

If the json() method is asynchronous, it's important to include an additional await:

async fetchDashboard(projectId, projectUserId) {
  try {
    const events = await (await this.apiHttp
      .fetch(`${projectId}/users/${projectUserId}/dashboard-events`)).json();
    return events;
  } catch (error) {
    // If fetching fails, default to local data for testing purposes
    return await (await this.http
      .fetch(`${this.appConfig.url}dist/api/query/json/dashboard-events.json`)).json();
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Struggling with Mongoose's Inaccurate Value Saving

When I attempt to create an object from a post request, I notice that the fields coming from the request body are being set to the field name itself. Strangely, I am not receiving any errors but the JSON object I expect in the response is not what I am get ...

Utilizing ng-bind-html to establish Angular bindings within the HTML code

My scenario involves hitting a specific route (#/abc) and then making a POST request to the server to render the HTML received as a response. Instead of embedding this logic directly into $routeProvider.when, I came up with my own solution. This is how I ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

trigger an event from a different event in Node.js

I am attempting to retrieve the list of newly connected users in admin.html client.html (client login authentication) admin.html (notify new user join) server.js app.get('/', function(req, res){ res.sendfile('client.html'); }); ap ...

Limits of the window in a d3 network diagram

I'm currently working with a network diagram that consists of circle elements and lines connecting them. However, I've run into an issue where sometimes there are so many circles that they extend beyond the edge of my screen (see image attached). ...

Struggling to make HTML5 geolocation coordinates function properly

I've attempted to work with examples in this code snippet, but I'm struggling to make the html5 geolocation coordinates function properly. Everything works fine when I hardcode the coordinates. var infowindow; var map; function initialize() ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

When attempting to access the ref of a Text Input in a React Native Component, the refs are found

In my application, I have multiple components each containing a textInput field. When a user submits the textInput in one component, I want it to automatically focus on the next component's textInput field. However, when I try to implement this functi ...

Why is the useContext array appearing empty when accessed in a function within the same context, despite being pre-populated?

I am encountering an issue with my useContext setup, where I provide all logged-in users. When the app runs initially or when users log in, the array is populated with all current users on the server, which works as intended. However, when the "user-connec ...

Manipulate the CSS style of the body element in Angular with Typescript using the important tag

Within my Angular application I have implemented the following code to customize the body style: constructor(private elementRef: ElementRef) { } ngOnInit() { this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden'; ...

Ways to prevent browser scrolling on smartphones and tablets

Having a simple HTML file with an iframe embedded, I have been attempting to prevent my browser from scrolling in both documents. However, this solution works intermittently and does not provide consistent results. I have tried applying various event list ...

Issues with React-markdown, including malfunctioning gfm tables and various other difficulties

My journey to render markdown in react using the react-markdown library has hit a few bumps along the way. I've encountered 2 issues and have been pondering 1 question that remains unanswered: Upon implementing the remark-gfm plug-in, the tables fail ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

There should be a delay in the code following the ajax (code) block

Initially, my question was lengthy and accompanied by the complete code. However, it has now been condensed. function displayRecords(table) { myTable.fnDestroy(); $.ajax( { data: "tableName=" + table, url: "showTable.php", ...

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

The global coordinate system is used to determine the direction of raycasting, not the local coordinate

Using the raycasting method to detect various colored strips on both sides of the track, I am able to keep my car object in position by calculating the distance. However, the issue lies in the fact that the ray always points in a constant direction in the ...

Implementing Pagination or Infinite Scroll to Instagram Feed

Currently, I am working on creating an Instagram feed for a fashion campaign where users can hashtag their photos with a specific tag. Using the Instagram API, the script will pull all recent posts with this common tag to display on the webpage. Instagram ...

Toggle the class of a selected data attribute on another div when clicked

With a click event, I attempt to dynamically add/remove classes by using data attributes on another div. Upon clicking "Text 2," the initial display of "FLAG 1" is set to none, and the background color of "DOT" should change. The association between the t ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...