Encountering the error message "Uncaught (in promise) Error" while inside a catch block

I've been struggling with a puzzling error for nearly a day now. It appears that my rejected promise is slipping through without being caught by the catch block. While I'm relatively new to using es6, async, and await, it does remind me of concepts I am familiar with in C#.

Get: async function (request, cancelToken = null) {
console.info('Sending GET', request)
store.commit('global/setLoader', true)
let headers = getAuthTokenHeader()
try {
  var res = await Vue.axios({
    url: baseUrl + request.Url,
    params: request.Params,
    method: 'GET',
    headers
  }).catch(function (error) {
    console.error('Failed to GET: ' + error)
    if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {
      throw new Error(error.response.data)
    } else {
      throw error
    }
  })
  console.info('Request received', res)
  return res
} finally {
  store.commit('global/setLoader', false)
}
},  

The issue arises on the line

if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {

Based on information from https://javascript.info/async-await#error-handling
I shouldn't be seeing this "Uncaught (in promise)" error because I have the entire asynchronous call wrapped in an await.

The calling code also waits for the completion of this code execution. Here is how the call looks like for reference.

static async GetPackagingDimensions (input, Id) {
const request = {
  Url: 'api/packing/getPackagingBoxDimensionsByBarCode',
  Params: {
    boxBarcode: input,
    orderId: Id
  }
}
const res = await HttpUtil.Get(request)
return res

}

Interestingly, if I enclose the calling code itself within a try catch block, the error gets caught appropriately.

What could possibly prevent me from catching the rejected promise within my catch block?

Quick Edit - Even my console.log statement within the catch block is not getting executed, indicating that the error surfaces beyond that point.

https://i.sstatic.net/9KVLD.jpg

Answer №1

When it comes to try catch blocks, they don't function the same way as then catch.

try {
  var result = await Vue.axios({
    url: baseUrl + request.Url,
    params: request.Params,
    method: 'GET',
    headers
  })
}
catch(error) {
    console.error('Failed to GET: ' + error)
    if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {
      throw new Error(error.response.data)
    } else {
      throw error
    }
}

This is an example of using try catch blocks in JavaScript. The await keyword resolves the promise.

If any errors occur during the promise resolution, the error is thrown to the catch block.

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

What steps are needed to have AJAX retrieve data from the controller within an MVC framework?

So, I am struggling with making an AJAX call in my project. I need to return a string as a JSON object from the controller back to the view where the ajax call is made. Despite numerous attempts, I have been unable to achieve this successfully. My main que ...

Any advice on how to navigate to a different screen based on the content of a dynamic grid view?

I have a grid view displaying data from my database, with each title representing a separate box. When a title in the grid view is clicked, I want to redirect to a corresponding screen. How can this be achieved? For example, clicking on "Orders" should re ...

Vue.js video player component displays at a width of 100 pixels

I recently started implementing the vue-video-player library into my project. However, I'm facing an issue where the player renders at a width of only 100px. I'm not sure why this is happening or how to adjust it. After going through the documen ...

Is there a way for me to extract an image from Open Flash Chart 2?

After attempting to follow this tutorial, I discovered that it was not functioning properly. Although my server side is operating correctly, I encountered an issue in Firefox when trying to access the instance of ofc and call post_image. The error messag ...

Guide to creating several AJAX requests using a for loop

I'm currently experimenting with the Star Wars API (SWAPI) and attempting to display the names of all the planets. However, the planet information is spread across multiple pages. How can I go about making several AJAX requests in order to retrieve an ...

Add axios requests to the axios.all array

Good evening. I am currently trying to insert an array into the axios.all([]) structure! This is the code snippet I am working on: app2.js new Vue({ el: '#central', data: { estilo: 'resize:none;text-align:center;color: ...

"At the beginning of an array in JavaScript, I often encounter the issue of receiving

Here is some code that I created: function get_coordinates(container) { var x; var y; var divs = container.getElementsByTagName('div'); Array.from(divs).forEach(div => { y += div.offsetTop+" "; x += d ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

What is the process for importing the util module in Node.js?

I attempted to use the isDeepStrictEqual() method for object comparison but encountered this error: util.isDeepStrictEqual() is not a function After checking the official documentation, I found out that this method was introduced in Node.js v9.0.0 w ...

Issue arises with variable not defined upon submission of ng-change event

Currently, I am attempting to save a variable from the date type input in HTML using AngularJS. In previous instances within this application, I was able to accomplish this with select tags instead of input tags and everything worked perfectly, confirming ...

The continuous resizing of the window is triggering a loop in flexslider when the resize function is called

I am currently working on a website that utilizes the flexslider plugin. My goal is to detect when the browser window is resized, and then reinitialize the slider so that it can adjust its size and other parameters accordingly. Initially, I was able to a ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

Update depth has exceeded the limit, the useEffect in React is causing issues

I encountered a strange error while working with the component below. The error seems to occur only when I make changes to the file, like altering a default prop, and then saving the file. I believe the issue stems from the props triggering a re-render, as ...

Leaving the Node Environment after Completing All Promises

Just a heads up, this is a cronjob, so I'll have to exit using a process.exit command once the processing is done. In this unique scenario, I'm going to illustrate the problem with some placeholder code because pasting the exact script could lea ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

Using React JS to extract query string values

My current URL contains the following: http://example.com/callback?code=abcd I am trying to extract the value of "code." Here is the React code I have written: import React from 'react'; import { useEffect } from 'react'; const Callba ...

Attempting to access the server route does not involve the function str.CharAt

I seem to have encountered an issue while trying to deploy an API to Heroku. Initially, everything was running smoothly on my local machine, but at some point, I must have made a mistake, resulting in a broken setup. When I access the page using just local ...

Having trouble defining the chosen option through JavaScript

I encountered an issue while attempting to set the selected option through JavaScript. I have created a select element and populated it with options from MySQL using PHP, like so: <select class="form-control input-group-lg" name="progress ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...