What is the best way to obtain an error as an object when subscribing to an HTTP GET request

I am working on an asp.net core webApi along with an Angular9 WebApp.

My goal is to retrieve the error in a subscribe as an object rather than just a string.

this.http.post<TestSystem>(this.url, testsystem).subscribe((result) => {
   // do something
}, err  => {
    console.log(typeof err);
});

The asp.net core backend method returns

        [HttpPost(template: "save")]
    public ActionResult<TestSystemBean> Save(TestSystemModel model)
    {
        // Validate reportRequest
        if (ModelState.IsValid == false)
        {
            return BadRequest("Invalid ModelState");
        }
    }

However, I am only receiving the string 'Bad Request' and not an object containing the message 'Invalid Modelstate'. How can I retrieve the error as an object?

Within the ErrorInterceptor of the AngularApp, I am getting a detailed HttpErrorResponse:

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
  debugger;
  if ([401, 403].includes(err.status) && this.authenticationService.userValue) {
    // auto logout if 401 or 403 response returned from api
    this.authenticationService.logout();
  }
  const error = (err && err.error && err.error.message) || err.statusText;
  return throwError(error);
}))

}

Answer №1

After much trial and error, I finally figured it out. Eliminating the following line made all the difference:

const error = (err && err.error && err.error.message) || err.statusText;

I'm still not entirely sure what was happening there, but removing it allowed me to get the HttpErrorResponse exactly as needed.

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

Creating an Angular Universal Dockerfile and docker-compose.yml file: A step-by-step guide

After struggling to Dockerize my Angular universal app and integrate it with an existing dockerized Spring Boot REST backend, I found myself hitting a wall in terms of available resources and assistance online. Despite making various adjustments, the Docke ...

The best practices for utilizing ES6 Modules syntax in TypeScript files within a NextJS environment

The issue appears to be trapped in a loop: package.json is missing type: "module". This results in an error when trying to use modules in TypeScript files: An error occurred while running the seed command: /Users/me/code/me/prisma-learning/grap ...

Guide on linking enum values with types in TypeScript

My enum type is structured as follows: export enum API_TYPE { INDEX = "index_api", CREATE = "create_api", SHOW = "show_api", UPDATE = "update_api", DELETE = "destroy_api" }; Presently, I have a f ...

Sign up for the identical Observable within a Child Component in Angular 2 using TypeScript

This question may seem simple, but as a newcomer to Angular 2, I often find myself needing more explanation despite the good examples and tutorials available. Within a component, I have an observable that gets updated periodically. While I've simplif ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Angular 10 experiences issues with JWT Helper service causing errors

Currently, I'm facing an issue with my Angular 10 project and the latest JWT Helper service. Unfortunately, the app is failing to compile. The error message that pops up reads as follows: ERROR in node_modules/@auth0/angular-jwt/lib/jwthelper.servic ...

Mastering the art of leveraging generics in conjunction with ngrx actions

Currently, I am in the process of developing an Angular 7 application that utilizes the NGRX store. In our application, we have numerous entities, each with its own dedicated list view. I decided to explore using generics with the NGRX store to avoid writi ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

There are no route parameters defined

Within my user template file, I have a tab control implemented as shown below: <nav md-tab-nav-bar> <a class="tab-label" md-tab-link [routerLink]="'following'" routerLinkActive #following="routerLinkActive" [acti ...

Uh oh! We encountered an error: Uncaught (in promise): Error: No routes found for the provided URL segment

There seems to be an issue with the router in my Angular application. I have successfully deployed it on an Apache server for production, and it is being served from the URL www.domain.com/clientng. Everything works fine, but I encounter an error in the br ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Exploring methods to validate a Reactive Form in Angular 10+ by incorporating two groups within the formBuilder.group

I am looking to implement form validation with two separate groups within the main formBuilder.group. I am unsure of how to access the 'errors' value in my HTML [ngClass]. component.ts: createForm(): void { this.myForm = this.formBuilder ...

Pass a photo along with additional characteristics to the post endpoint in the API

Using the code snippet below, I am able to send an image to a post method and save it as a BLOB in the database successfully: Angular Code: public postUploadedFile(file:any){ this.formData = new FormData(); this.formData.append('file',fi ...

Exploring the process of connecting to an additional database with Angular Fire

I came across this code snippet: import { FirebaseApp } from "@angular/fire/compat"; import { AngularFirestore } from "@angular/fire/compat//firestore"; import { initializeFirestore } from "@angular/fire/firestore"; impo ...

Vue version 3 is encountering an issue with a module that does not have an exported member in the specified path of "../../node_modules/vue/dist/vue"

After I updated my npm packages, errors started popping up in some of the imports from the 'vue' module: TS2305: Module '"../../node_modules/vue/dist/vue"' has no exported member 'X' The X instances affected inclu ...

Unable to verify the authenticity of every file I choose to upload

Currently, I am in the process of learning how to develop a mean stack app, specifically focusing on creating an ecommerce type application. The main issue that I have encountered revolves around image uploading. My goal is to upload multiple files simult ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...