Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable operators for error handling in an Angular project. This approach was unfamiliar to me, prompting me to suggest implementing the built-in .catch observable operator instead. Here is a TypeScript example of what I observed:

public getSomething(id: string): Observable<any> {
    try {
      return this.http.get('someurl/someparam')
        .map((res) => res.json().data);
    } catch (e) {
      throw new Error('Error with getSomething()');
    }
  }

Despite my suggestion, there was resistance from the team arguing that it would not impact performance in terms of memory or network. However, I pointed out that the try/catch block does not accurately capture errors from the HTTP request. Therefore, I am curious to know whether wrapping the http.get in a try / catch indeed affects performance. Additionally, I always believed that try / catch was primarily used for synchronous code rather than asynchronous operations.

If my question seems vague or inappropriate, please feel free to let me know, and I will remove it. I am eager to hear other developers' perspectives on this matter.

Answer №1

Someone mentioned that it wouldn't impact performance in any way (neither memory nor network)

While that may be true, the real issue lies in the correctness of the code.

The modification could result in a substantial improvement in handling errors: try/catch deals with synchronous exceptions, whereas .catch() manages errors from the observable - including asynchronous ones.

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

Can multiple modules that are lazily loaded be active at the same time?

We're excited about our upcoming project that will feature a tab-based UI design. Each tab will represent a different feature module, loaded lazily to improve performance. Our goal is to allow users to switch between tabs seamlessly and keep previousl ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

Guide to implementing CRUD operations on a remote MongoDB using Node.js

Recently, I delved into the world of NodeJS and discovered its server-side capabilities. My current project involves interacting with MongoDB on a remote server using the nodejs mongodb driver. With just a few lines of code, I am able to connect to the dat ...

Utilizing AngularJS to retrieve and showcase information from a single post through the WordPress API

Utilizing the WordPress API as a data source for an AngularJS/Ionic application, I have a post type named programmes. The JSON structure of the programmes includes: var programmes = [ { id: 6, title: "A post", slug: "a-post" }, { id: 7, title ...

Encountered a glitch while trying to install React JS using npx create-react-app xyz

After entering the command in the terminal, I encountered an error stating: npm Err! code-ENOENT npm Err! syscall lstat npm Err! path Interestingly, this same command worked perfectly on my instructor's laptops. For reference, I have attached a snaps ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

Resetting the Angular2 poller in an ng-bootstrap accordion

I am currently utilizing a multi-dimensional array connected to a reactive poller that waits for a database state update. Interestingly, when I initially load the state once, the user interface functions as intended. However, a challenge arises when I act ...

AngularJS Instant Search is experiencing significant delays

Currently, I am developing a database with a web front-end. In the previous versions of this project, I utilized jQuery. However, I have now transitioned to using AngularJS for the "instant-search" feature, as shown below: function SearchCtrl($scope, $htt ...

What exactly is the function of registerServiceWorker in React JS?

Just starting out with React and I have a question about the function of registerServiceWorker() in this code snippet: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServi ...

Is there a way to delete a stylesheet if I only have limited information about the url?

I am attempting to dynamically remove a CSS stylesheet using JavaScript or jQuery. I am aware that the target stylesheet is located within the 'head' element and includes the text 'civicrm.css', however, I do not possess the full URL o ...

A guide on dynamically adding a CSS stylesheet to an Angular component during runtime

I have a requirement to dynamically inject a stylesheet into a component at runtime. The CSS url needs to change depending on user configuration settings and the selected theme. Using styelUrls for static injection won't work in this case, as it is s ...

Angular continually monitors changes for dom-to-image and generates countless renders

I am trying to implement a feature in my Angular 4 application where child-components render wallpapers for themselves using dom-to-image-more. The issue arises when I try to dynamically render these child-components using *ngFor. The parent component h ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

transfer the form file to php using ajax requests

I am trying to send a file to PHP using AJAX. Below is the code I have written, but when I run it, I get an error saying "Undefined index: thefile". Can anyone help me identify the problem? HTML function sendData(url){ var xmlHttp = new XMLHttpRequ ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

Retrieve parent route parameters from a dynamically loaded route component

Struggling to access the parent route params in a lazy loaded route component using activatedRoute.parent.params. Despite this not working, I have managed to find a solution that involves fetching the value using an array index number which feels like a &a ...

Compelling users to upgrade to the latest version of the Angular 5 application

My Angular 5 application is currently deployed on Azure using ng build --prod. I am looking for a way to ensure that users are always prompted to download the latest version of the application, including any updates to style sheets. However, I have notic ...