Separate and handle multiple exceptions of the same instance individually

If I am facing the situation where multiple method calls to another class are possible, each of which could potentially throw the same exception that I am unable to modify, how can I handle each Exception separately without allowing the rest of the function to continue execution?

For instance:

async mightThrowExceptions() {

    var call1 = await this.api.sampleMethod(); //Possible exception of type 'E'
    //Should not proceed if call1 throws an exception
    var call2 = await this.api.dependantFrom1(call1); //Possible exception of type 'E'
    //Should not proceed if call2 throws an exception
    var call3 = await this.api.dependantFrom2(call2); //Possible exception of type 'E'

    /*
    If call1 throws an exception, perform:
    console.log('call1 threw exception');

    If call2 throws an exception, perform:
    console.log('call2 threw exception');

    If call3 throws an exception, perform:
    console.log('call3 threw exception');
    */
}

Answer №1

To increase readability, consider nesting try-catch blocks like this:

 try {
   const a = await getA();
   try {
       const b = await getB(a);
       try {
        const c = await getC(b);
       } catch(e) {
         // handle error from function C without affecting control flow
       }
    } catch(e) {
       // handle error from function B without affecting control flow
    }
 } catch(e) {
    // handle error from function A without affecting control flow
 }

A more elegant solution would be to differentiate the errors thrown by each function and handle them accordingly:

 try {
    await getC(await getB(await getA()));
 } catch(error) {
   if(error instanceof AError) {
      // handle error specific to function A
   } else if(error instanceof BError) {
       // handle error specific to function B
    } else if(error instanceof CError) {
        // handle error specific to function C
    } // add more conditions as needed
 }

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 is the best way to use async await to listen for an event in a child component with Vue-router?

To prevent users from unintentionally leaving an unsaved form, I am looking to implement a custom modal alert system with vue-router. Although the use of the standard browser alert box is an option, beforeRouteLeave (to, from, next) { const answer = wi ...

Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be w ...

Incorporating Layouts and Partials in Handlebars Template

Can you provide guidance on incorporating layouts and partials with handlebars templates like the example below? I have reviewed the documentation on partials but am still struggling to achieve my desired outcome. default.html The default layout is util ...

Is jQuery AJAX returning improperly formatted JSON when using the jsonp type?

$('#rn_s').keyup(function() { var rn = $('#rn_s').val(); if(rn.length == 9) { $.ajax({ url: 'http://routingnumbers.info/api/data.json?rn=' + rn, type: 'GET', dataT ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

I am facing an issue where Bootstrap button classes are duplicating when I inspect the code. How can I resolve this

Can anyone help me with an issue I am facing with a Bootstrap button? Despite using only the btn btn-default classes, when inspecting it in Chrome, multiple classes are being displayed on the button. I'm unable to figure out why this is happening and ...

function for ajax response is received

How can I replace HTML code with the 'for from django' function using a jQuery AJAX call? $.ajax({ url: url, data: ...

Retrieving data from a stored procedure with XSJS and storing it in a variable

I am currently facing a situation where I need to pass a session user as a parameter to a stored procedure in order to retrieve a receiver value. This receiver value needs to be stored in a variable so that I can use it in another function within an xsjs f ...

Begin by adding the sub Route at the start of the route path in Angular

How can I dynamically add a user's name to all routing pages in my Angular project when they type the URL like www.mysite.com/hisName? The desired result should be www.mysite.com/hisName/home This is the routing code I have: import { NgModule } from ...

Converting Numerical Formats into Numbers: A Step-By-Step

How can I format numbers in JavaScript as 1,000,000 without being able to use the operators +, -, *, or / with numbers inputted into a specific box? After clicking "try it," an error message is displayed: ORIGINAL AMOUNT: NaN ORIGINAL AMOUNT: NaN ...

Ways to modify the height of Material UI header using custom styling

How can you customize the dimensions of the header in a Material-UI table, such as height and width? <TableHead > <TableRow > <TableCell hover>Dessert (100g serving)</TableCell> <TableCell align="right">Cal ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Retrieve a particular element from an array within a JSON object using Ionic

I am currently facing a challenge in extracting a specific array element from a JSON response that I have retrieved. While I can successfully fetch the entire feed, I am struggling to narrow it down to just one particular element. Here is what my service ...

Using Angular with THREE JS integration in Javascript

I am currently experimenting with Angular and facing a challenge that I can't seem to figure out. The issue I am encountering involves integrating a javascript code, SunLight.js, from the repository https://github.com/antarktikali/threejs-sunlight in ...

Correct validation is not achieved when the "!" symbol is used in the matches function

I am working on a React and Next.js project where I am using Formik for handling forms and Yup for validations. One specific input field requires some validations to be performed. This field must be required, so if the user does not enter any information, ...

Can you provide an overview of the ternary operator within advanced method signatures in TypeScript?

I'm struggling to understand the method signature provided below: export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; This code snippet was in response to a question on c ...

The program encountered an issue: Unable to access the 'push' property of a null object

I am facing an issue while trying to add an item to a list, and the error message is displayed below: import { Injectable } from '@angular/core'; // import { AngularFire, FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase } fr ...

Calculate the average value of the properties of a jQuery object

Consider the object below: rating { atmosphere: 85 cleanliness: 91 facilities: 91 staff: 85 security: 94 location: 78 valueForMoney: 85 } I'm looking to calculate the average of all these property values. Can y ...

Attention Needed - Certain vulnerabilities necessitate manual review for resolution

npm audit === Security Report from npm audit === # You have 1 vulnerability that can be resolved by running `npm update terser-webpack-plugin --depth 3` Severity Issue ...

Sprockets could not locate the file for jquery.atwho

I have been attempting to integrate the jquery-atwho-rails into my application, a Rails gem designed for at.js. I have followed all the steps provided, executed bundle install, included the necessary code in both application.js and application.css, stopped ...