Personalized angular subscription malfunction

Recently, as I dive into learning Angular 6, a question has arisen regarding the subscribe method and error handling.

A typical use of the subscribe function on an observable typically appears like this:

this.myService.myFunction(this.myArg).subscribe(
  // Retrieving data from the service
  data => {
    this.doSomethingWith(data);
  },
  err => console.log('An error occurred: ', err),
  () => console.log('Process complete!')
);

In this scenario, an error could be a 500 status code or similar, but my curiosity lies in finding a way to structure the data sent from my backend (utilizing PHP) so that the subscribe function can interpret it as an error. For instance, envision an application where users build a list of items from a defined finite set (let's say, the collection of all Pokemon), if a user tries to add a non-existing Pokemon, I want the backend to signal an error. Presently, I return a JSON object like this:

{ "error" => "you did something wrong" }
and handle it within the first argument of my subscribe function. While this works fine, I ponder if there are established methods for efficient error handling that would be worth implementing. Cheers!

Answer №1

Consider trying the following approach:

import {
    HttpEvent,
    HttpHeaders,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpRequest
} from '@angular/common/http';

this.myService.myFunction(this.myArg).subscribe(
  // Retrieving data from the service
  data => {
    this.handleData(data);
  },
 (err: any) => {

        if (err instanceof HttpErrorResponse) {
              switch (err.status) {
                   case 400:
                     console.log("Error 400")
                     break;
                   case 401:
                     console.log("Error 401")
                     break;
                   case 500:
                     console.log("Error 500")
                     break;
          }
       }
);

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

Visual Studio fails to acknowledge changes made to TypeScript files and incorrectly assumes that the project is up to date

I am currently utilizing TypeScript in a project based on ASP.NET Core 3 (preview 5), using the latest version of VS 2019 16.1.1 (tsc: 3.4). Whenever I perform a "Rebuild All" or make changes to any C# files or even modify the tsconfig.json file, all my T ...

Manually close the AntD Menu without using any shortcuts

I'm facing a unique situation with my table implemented using antd. Each row has a dropdown menu that opens a modal upon clicking. To ensure the dropdown menu doesn't trigger the row click event, I used stopPropagation on the menu item click. Eve ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

Avoid including redundant node modules in the war file

Currently, I am working on a web application that utilizes Maven, Spring, Hibernate, and Angular. The issue I am facing is the large size of the war file, which stands at 151 MB. Out of this total size, a significant portion of 107 MB is occupied by unne ...

The error message "Type 'null' cannot be assigned to type 'Element | DocumentFragment'" occurs when using Nextjs/React createPortal

I am completely new to typescript. Currently, I'm working on a project that has a lot of pre-configured react components in JavaScript files (.js). My task now is to convert everything to TypeScript (.tsx) without triggering any ESLint errors. Unfort ...

Is there a way to position the label to the left side of the gauge?

Is there a way to position the zero number outside the gauge? I'm having trouble figuring out how to do it because the x & y options won't work since the plotLine's position keeps changing. The zero needs to move along with the plotLine and ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Encountering a problem where I am unable to input text in a textbox after making changes

I'm having trouble editing a text field. I can't seem to type anything when trying to edit. Strangely, everything works fine when adding a user, but the issue only arises during editing. Take a look at my code below - const initialState = { ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Retrieve fresh information every 30 seconds utilizing the useQuery hook in React

I am utilizing '@tanstack/react-query' to retrieve data in my React + Typescript application. Below is a snippet of my code, where I aim to fetch metric data every 30 seconds import { useQuery } from '@tanstack/react-query'; import ...

The communication between the child and parent components is failing to function correctly

I'm trying to send data from a child component to a parent component, but the function isn't being invoked correctly. It doesn't seem to work as expected. <router-outlet (activeElement)='getActive($event)'></router-outlet ...

Encountered an error while attempting to load http://localhost:9999/auth-service/oauth/token: The response for preflight request returned an unexpected HTTP status code

When attempting to generate an OAuth2 token, I utilized Spring Boot OAuth2 and Angular 5. In Postman and curl, I successfully generated the token by providing the appropriate values. However, when using the same parameters in the Angular POST request, it ...

How can I activate caching with Prerender.io?

After successfully setting up prerender on my local machine, everything is working smoothly with all pages properly prerendered. However, the process always takes 5-10 seconds. Does anyone have a recommendation for implementing caching on a local Prerend ...

Conditional void parameter type in Typescript

Attempting to create a custom Error class that can handle different data based on the error code seemed like a complex task for TypeScript. However, surprisingly, it was successful: const enum ERROR_CODES { E_AUTHORIZATION = 'Authorization error&ap ...

There seems to be an issue with the 'clr-icon' element; it is not recognized as a valid element

When I run this specific command: ng build --prod --base-href ./ An error message is displayed: ERROR in : 'clr-icon' is not a known element: 1. If 'clr-icon' is an Angular component, then verify that it is part of this module. 2. If ...

Issue with Typescript Conditional Type not being functional in a function parameter

For a specific use-case, I am looking to conditionally add a key to an interface. In attempting to achieve this, I used the following code: key: a extends b ? keyValue : never However, this approach breaks when a is generic and also necessitates explicit ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

Unable to extract the 'data' property from an undefined source in React, causing an error

I encountered this error message: TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined. export const getServerSideProps: GetServerSideProps = async () => { // categories const { data: categor ...

What is the correct way to nest multiple ng-if statements?

I'm currently grappling with a problem involving multiple nested ngIf directives applied to ng-template elements in Angular.js, and I've yet to find the ideal solution. While I am aware of workarounds, they are not as efficient as I would like th ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...