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

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

Issue: The system needs the 'image' property to proceed (Dall E's image variation API by OpenAI)

Utilizing the Dall E Create image variation API has been a bit challenging for me. Every time I send a post request, I encounter this particular error: error: { "code": null, "message": "'image' is a required property&q ...

Easily Organize Your Data with Kendo React Grid: Rearrange Columns and Preserve Your Custom Layout

Currently, I am working on implementing a Kendo React grid with the option set to reorderable={true} for allowing column reordering. However, I am facing difficulty in determining how to save the new order of columns. Which event should I use to detect whe ...

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: I haven't made any changes to my project's code (confirmed by running git status). It's unclear whethe ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Displaying exclusively the country code in an Angular material-select component

This is the HTML code I am using: <mat-form-field style="width: 70px;margin-left: 50px;"> <mat-label>Select an option</mat-label> <mat-select (openedChange)="toogleCountry()" [(value)]="selected"> <mat-option value="+91" ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Understanding how to handle POST data from an Angular2 application in PHP

I am trying to establish a connection between my angular2 application and PHP backend. My desired approach is as follows: this.http.post('/users/create', {email: email, password: password}); However, I am encountering an issue where the $_POST ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Tips for successfully passing a closure as a parameter in a constructor

I encountered an issue while working with a third-party library where I needed to register my own control. The problem arose when I tried to add another dependency to the control and struggled with passing a closure as a parameter to fulfill the required c ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

What are the reasons for deprecating bindToController in Typescript?

When I am creating an AngularJS directive using TypeScript, I typically use the bindToController property to bind parameters to the controller for easy access. export class MyDirective implements IDirective { controller = MyController; controllerA ...

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

How to use Angular2 Router to redirect a state to its default substate

How can we implement a default substate in the new Angular2 Router? For instance, I would like the router to automatically direct from /user to /user/profile, creating a default substate for user. ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...

Issues installing dependencies in Angular using npm

Today I attempted to create a new project. I used the following command: ng new NAME --style=less However, when I ran this command in my cmder, it resulted in errors and warnings. To troubleshoot, I decided to uninstall Node.js along with the files in R ...

Issues encountered when attempting to utilize ng-autocomplete 2

Attempting to implement ng2-autocomplete by following the documentation at https://www.npmjs.com/package/ng2-completer I have been encountering various errors every time I attempt solutions from Stack Overflow or GitHub. Any assistance in resolving this i ...