Handling HTTP errors in Angular when receiving a JSON response

I'm struggling to resolve this issue and I've searched online with no luck. The problem lies in my post call implementation, which looks like this:

return this.http.post(url, body, { headers: ConnectFunctions.getHeader() }).pipe(
  map(result => {
    return result;
  }),
  catchError(ConnectFunctions.handleError(url, []))
);
}

Upon making the request, the server responds with the following:

{"status":500,"timestamp":"21-07-2020 03:51:17","message":"my custom message","details":"some details"}

I am aiming to extract the value of the "message" field ("my custom message"), but so far I haven't been successful.

public static handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
        console.log("Error use: " + `${operation} failed: ${error.message}`);
        console.log("Error statusText: " + error.statusText);
        return of(error as T);
    };
}

Any suggestions on how I can achieve this?

Thank you for your assistance.

Answer №1

If you're looking to detect errors, here is a concise way to do so:

return this.http.post(url, body, { headers: ConnectFunctions.getHeader() })
      .catch((err: HttpErrorResponse) => {
    // You can customize the logging or take other actions as needed
    console.error(err.error.message);
  });

To learn more about HttpErrorResponse, visit: https://angular.io/api/common/http/HttpErrorResponse

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

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Navigating Angular 2 v3 router - accessing the parent route parameters within a child route

My route is configured as /abc/:id/xyz The abc/:id portion directs to ComponentA, with /xyz being a nested component displayed within a router-outlet (ComponentB) Upon navigating to /abc/:id/xyz, I utilize this.route.params.subscribe(...) (where route is ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

A guide to properly executing initialization functions in Angular with Electron

Currently, I am working with Angular and Electron. I have a Preferences object that I need to initialize (Preferences.init()) before any other code is executed. Is there a specific location in Angular or Electron where this initialization code should be pl ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

The flag will never turn true; it's stuck in the false position

Currently, I am in the process of developing a custom hook to store data on a server. To mimic the server call, I have implemented a simple setTimeout function that changes the value of the data creation flag to true after 2 seconds. I have a specific fun ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

Angular 2+: The art of creating an instance of a class using data retrieved from the backend

Within my Angular app, I have a Customer class and an ICustomer interface. interface ICustomer { <-- obtained from backend id: number; name: string; address: string; // additional properties } class Customer { <-- widely used in th ...

Using FormArray in Angular 2 with ControlValueAccessor

My child component manages an array of input controls and I would like to implement a form control over this child component. I am passing an array of JSON objects and I am wondering what is the correct way to bind the parent form to the child component&a ...

Filtering Deno tests by filename: A step-by-step guide

How can I selectively run Deno tests based on their filenames? Consider the following test files: number_1_test.ts number_2_test.ts string_test.ts If I want to only run tests with filenames starting with number*, I am unable to use either of these comma ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Simultaneous requests and parallel execution

Within my NodeJS service, I have implemented a process to retrieve user details from a database and send them to another application via http. Processing each user record individually is slow, especially with millions of records. To address this issue, con ...

Building a seamless service across all components in Angular4

In every service, there is a need for a shared common service that will only be created once. For example, let's call this common service - export Class CommonService { _commonVar1= ""; _commonVar2= ""; } Now, the instance of the common ...

Angular 2 does not recognize the existence of .then in type void

I have a query regarding Angular2 and I'm struggling with the void function in my code. Can someone help me out? I am new to Angular2 and unsure of what needs to be added in the void function. Check out this image for reference export class PasswordR ...

Encountering [Object Object] within an angular2 app

https://i.stack.imgur.com/iceKH.pngI recently created an angular2 application using ngrx/effects for handling http calls. My reference point was an application on GitHub. However, I am facing an issue where the response from the HTTP call is not displaying ...

The HTTP GET method is functioning properly, however, the other HTTP methods are returning a 401 error in the context of Angular 9 and Asp.Net Core

Reported Issues: The JWT authorization functionality is working as intended, allowing only authorized users to access protected methods via GET requests. GET requests are functioning correctly without any issues. However, when it comes to POST, PUT, and ...

What is the process for obtaining an app icon from the store using Angular?

Currently, I am working on an app using ionic, angular, and Cordova. Within this app, there are links to other apps available in the app store. My main query is: Is there a way to retrieve the icons of these apps from the store? I aim to display these ic ...