Mastering the HandleError Function in Angular's Tour of Heroes

I've been diving into this tutorial:
https://angular.io/tutorial/toh-pt6#error-handling

I'm struggling to grasp the concept of error-handling with the function: handleError.

This function is utilized in the following code snippet:

/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(heroes => this.log(`fetched heroes`)),
      catchError(this.handleError('getHeroes', []))
    );
}

Here's the definition of the handleError function:

/**
 * Handle Http operation that failed.
 * Let the app continue.
 * @param operation - name of the operation that failed
 * @param result - optional value to return as the observable result
 */
private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // TODO: better job of transforming error for user consumption
    this.log(`${operation} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

I am puzzled by the syntax of:

return (error: any): Observable<T> => { ... }
?

Could it be interpreted as:

return ((error: any): Observable<T>) => { ... }
?

I am curious about the origin and purpose of this function.

The more insight you can provide on the inner workings of the handleError function, the better. I want to delve deep into its logic.

Answer №1

When there is only one parameter name, parentheses become optional. For more details, refer to arrow_functions

(param1, param2, …, paramN) => { statements } 
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }

// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }

Generic

This feature allows capturing the type provided by the user, serving as a type check method in Typescript.

Reference:


In this example, T is used again as the return type. By observation, we can see that the type is utilized for the return type.

private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    ...

    return of(result as T);
  };
}

In the following example, I will illustrate how generics work with string and number types.

// string type (maybe you want to return some message when error)
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      ...
      catchError(this.handleError<string>('getHeroes', 'my result....'))
    );
}

// similar to : private handleError<number>(operation = 'operation', result ? : number)
//  return (error: any): Observable <number> => { ...
private handleError<T>(operation = 'operation', result? : T) {
  return (error: any): Observable<T> => {

    ...

    // result: my result....
    return of(result);
  };
}


----

// number type (maybe you want to return ID:1234) when error
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      ...
      catchError(this.handleError<string>('getHeroes', '1234'))
    );
}

// similar to : private handleError<string>(operation = 'operation', result ? : string) 
//  return (error: any): Observable <string> => { ...
private handleError<T>(operation = 'operation', result? : T) {
  return (error: any): Observable<T> => {

    ... 

    // result: 1234
    return of(result);
  };
}

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

Error: The TranslateService provider is not found and needs to be added to the

When attempting to make translation dynamic in angular2 using the ng2-translation package, I encountered an error message: Unhandled Promise rejection: No provider for TranslateService! zone.js:388Unhandled Promise rejection: No provider for TranslateSe ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

Determining the data type of an object key in Typescript

Is there a way to limit the indexed access type to only return the type of the key specified? interface User { id: string, name: string, age: number, token: string | null, } interface Updates<Schema> { set: Partial<Record< ...

Determining Checkbox State in Angular 2: A Simple Guide

I have a set of checkboxes displayed like this: moduleList = ['test1', 'test2', 'test3', 'test4'] <li *ngFor="let module of moduleList"> <input [value]="module" type="checkbox"> {{module}}<br> < ...

Is Angular CLI incorrectly flagging circular dependencies for nested Material Dialogs?

My Angular 8 project incorporates a service class that manages the creation of dialog components using Angular Material. These dialogs are based on different component types, and the service class is designed to handle their rendering. Below is a simplifie ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

Issue with CSS/JS resolved: figured out a way to create a page/menu that overlaps with their individual scrollbars

I am encountering an issue with a scrollbar that is related to a fullscreen menu appearing on a page and causing the page scrollbar to reset due to a display: none property. The images below provide a visual representation of the problem: Below is the Ty ...

Mastering the art of incorporating objects into templates using *ngFor Angular

Whenever I do my *ngFor loop in my HTML template, the data is displaying as [Object Object]. Below is my view with the enumerated data in the developer console: https://i.stack.imgur.com/KXmiI.png This is the snippet of my HTML code: https://i.stack.im ...

Using printjs in Angular to display properties with nested JSON objects inside another JSON object

I am currently utilizing the printJs library for printing and have added JSON object properties. It is functioning properly, but when the JSON object contains another JSON object inside, it displays [object object]. Does anyone know of a solution? PrintJ ...

What is the best method to determine the cumulative time spent filling out a text box on a web page using Angular?

I am working on a web page that contains two text boxes. My goal is to track the total time spent inside each box when the user clicks the submit button at the end of the page. clickInside() { this.text = 'clicked inside'; this.wasIns ...

Angular: understanding the intricacies of initializing variables within the *ngFor directive

I'm working with an Angular template that looks like this: <li *ngFor="let item of list | keyvalue" let-rand="random()"> <input type="radio" class="form-check-input" id="radio-{{rand}}" name ...

Spring Cloud Gateway is configured to redirect to Keycloak even if the route does not require authentication

Currently, I have a setup where a Spring Cloud Gateway is secured using Keycloak. This gateway serves as a keycloak client and sits in front of multiple microservices along with an Angular frontend that is hosted by an NGINX container. The security configu ...

The NestJS server encounters an unhandled exception leading to a server

As a newcomer to Nest.js and in the process of building a REST API server with typeorm, I have encountered an issue related to async functions. If I forget to include the await keyword while using an async function, it may result in an exception like &apos ...

Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below: // tslint:disable-next-line:max-line-length constructor(public addCustomerDialog: MatDialog, private router: Router, private rout ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

Issues with IonPicker displaying incorrect values

In my Ionic App, I am using the ion-picker component to display the selected text from an array of options. Although everything seems to be working fine and the console.log accurately displays the index value, there is a strange behavior when it comes to s ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Having trouble with Angular 2 hosting on Apache Server?

While working on my Angular 2 project and trying to host it on Apache server, I came across a tutorial on YouTube. However, when following the tutorial instructions to generate files in the 'dist' folder using "ng build --prod", I encountered an ...

fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Whoops! Looks like the module couldn't be located

After updating my ngx-translate-multi-http-loader from version 8.0.2 to 9.3.1, I encountered a module not found error. The error message is as follows: ./node_modules/ngx-translate-multi-http-loader/fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Err ...