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

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

Disabling the scrollbar within angular elements

Trying to remove the two scrollbars from this code, but so far unsuccessful. Attempted using overflow:hidden without success filet.component.html <mat-drawer-container class="example-container" autosize> <button type="button&qu ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Troubleshooting TestBed: Resolving the StatusBar Provider Error

After reading an informative article on testing Ionic2 projects with TestBed, I encountered difficulties when trying to replicate the example in my own environment. When attempting to initiate tests at Step 3, I encountered the error message stating "No pr ...

Unable to find any routes that match child routes using the new Angular 2 RC1 router

ApplicationComponent import { Component } from '@angular/core'; import {Router, ROUTER_DIRECTIVES, Routes, ROUTER_PROVIDERS} from '@angular/router'; import {SchoolyearsComponent} from "./schoolyear/schoolyears.component"; @Component({ ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

In what manner can I retrieve this particular type?

Can you provide me with an example of how to use this type? interface MyCode{ (): Function; title: string; } I've been thinking about various possibilities but haven't been able to figure it out. One approach is: let testCode: MyCode = ...

Setting values to variables within a component to enable universal access throughout the component in Angular 2

In my Angular 2 project, I have a function that retrieves data from a database using an API. I've created a function that stores the data successfully in a variable named "ReqData", which is of type "any". this._visitService.getchartData().subscrib ...

What is the reason behind typescript making it necessary for me to find a way to set a value of type

function f1() { const v : string = String(); if(v) {alert("IF");} // OK const b : boolean = v; // Type 'string' is not assignable to type 'boolean'. if(b) {alert("BOOLEAN");} } f1(); My approach to this issue involv ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

What is the method for specifying a null value in Typescript?

I'm curious if this code snippet is accurate, or if there's a better way to define it. Is there an alternative to using error!? I'm unsure of its meaning and would appreciate clarification. ...

What is the best way to insert an item into a tree structure when determining the appropriate level for insertion is necessary beforehand?

Currently, I am dealing with a tree-like object structure: interface Node { id: number; name: string; children?: Node[]; } NODE_DATA: Node[] = [ { id: 1, name: 'A' }, { id: 2, name: 'B', children: [ ...