JS- Catching Errors Inside and Outside

Imagine having 2 catch blocks in your code:

try {
axios.get('https://example.com', {})
  .then(function (responseOne: any) {
    return axios.post('https://example.com', {}, {})
  }).then(async function (responseTwo: any) {
    return axios.put('https://example.com', {}, {})
  }).then(async function (responseThree: any) {
    return axios.post('https://example.com', {}, {})
  }).then(async function () {
    reply.send
  }).catch(error) => {}
} catch(errorOuter) => {}

Based on my understanding, it seems like the outer catch will only be triggered if the first axios call is await axios.get(...). Is this assumption correct? What happens if each of the then blocks are also awaited?

If the code stays as it is, would the inner catch be the only one to be executed? If that's the case, then I can probably remove the outer catch altogether.

Answer №1

Is it correct that only the outer catch would be triggered if the first axios call was awaited using axios.get(...)?

Not quite.

The promise generated by

axios.get('https://example.com', {})
is resolved using then, as are subsequent promises until reaching the end of catch.

If you included await in line 2, you would await the promise from the catch() call.

The function provided to catch() collects and dismisses any error occurring within that chain of promises.

In this scenario, the code wouldn't reach the outer catch block.


If the code remains unchanged, will it always enter the inner catch? In that case, could the outer catch be removed?

Technically, yes; however, eliminating then and relying solely on await would enhance code readability.

try {
    await axios.get('https://example.com', {});
    await axios.post('https://example.com', {}, {});
    await axios.put('https://example.com', {}, {});
    await axios.post('https://example.com', {}, {});
    reply.send;
} catch (e) {
    // handle e
}

Answer №2

Looking at this specific scenario, it seems unlikely that the "outer" catch block (connected to the original try) will be triggered unless Axios encounters an error while trying to execute its asynchronous operation.

Each subsequent operation in the chained promises will eventually reach the .catch() method within that particular Promise if something goes wrong. However, the entire chain functions as one large asynchronous process, and the overall try block finishes and exits before this process reaches completion.

(To demonstrate this further, placing a console.log statement immediately after the code snippet provided would show that the statement is reached even before any of the AJAX operations have finished.)

In this case, the "outer" try/catch structure would only prove useful if you transition from using chained .then() callbacks to utilizing await. For instance:

try {
  const responseOne = await axios.get('https://example.com', {});
  const responseTwo = await axios.post('https://example.com', {}, {});
  const responseThree = await axios.put('https://example.com', {}, {});
  // etc.
} catch(errorOuter) {
  // handle error
}

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

Developing forms in Angular 5 involves the decision of either constructing a specific model for the form group inputs or opting for a more generic variable with two

As a newcomer to Angular, I've noticed that most courses and tutorials recommend using a model or interface for form data. However, I have found it more efficient and straightforward to just use a generic variable with two-way data binding. Could som ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Executing installed packages using npm: A step-by-step guide

Recently, I have encountered a confusing issue in my coding journey. In Python, I got used to installing packages and using them right away without any hiccups. For example, with SpotDL, everything worked seamlessly. However, things took a different turn w ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

The DAT GUI controls are mysteriously absent from the scene

Within a modal, I have set up a threejs scene with three point lights. All functions are exported from a separate file called three.ts to the modal component. The issue I am facing is that when I try to initialize DAT.GUI controls, they end up rendering ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format. This is my current process: public download(data: any): void { const documentCreator = new D ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Managing a click event with an element in React using TypeScript

Hey there, I'm pretty new to TypeScript and React. I have this event where I need to identify the element that triggered it so I can move another element close to it on the page. However, I'm facing some challenges trying to make it work in React ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Managing status in Angular applications

I am currently working on a project using Angular 7 and I have the following code snippet: public deleteId(pId){ return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response'}) .pipe(catchError(this.handleError)); } I ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

Typescript's interface for key-value pairing with generic types

Consider the example Object below: let obj1: Obj = { 'key1': { default: 'hello', fn: (val:string) => val }, 'key2': { default: 123, fn: (val:number) => val }, // this should throw an error, because the types of d ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

The 'cookies' property is not defined in the 'undefined' type

I am working on incorporating Google's Sign-In for Cypress tests using the following plugin: https://github.com/lirantal/cypress-social-logins/ (I am utilizing TypeScript). The code I have implemented is as follows: it('Login through Google&apos ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...