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

How can I determine if an Angular library is compatible with the specific version of Angular that my application is utilizing?

My Angular 8 application is currently running on a version that's quite outdated compared to the latest release of Angular. When it comes to incorporating Angular libraries, how can I determine if they are compatible with Angular 8? Is there a strict ...

Issue with ReactTS Route Triggering Invalid Hook Call

My implementation of the PrivateRoute component is as follows: interface Props { path: string, exact: boolean, component: React.FC<any>; } const PrivateRoute: React.FC<Props> = ({ component, path, exact }) => { return ( ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Set up Angular library by downloading from a specified local or network location

If I were to create an Angular library using the following commands: ng new libraries-workspace --create-application=false cd libraries-workspace ng generate library test-library After creating and building the library using the command below: ng build te ...

hosting on a base URL does not activate cloud functions

meta-tags-are-not-updating-for-root-url-www-domain-com Base url not triggered hosting I encountered a similar issue as mentioned in the first link above. The solutions provided seemed unusual, like having to delete index.html every time I build/deploy my ...

Calling a typed function with conditional types in Typescript from within another function

In my attempt to create a conditional-type function, I stumbled upon this question on Stack Overflow. Unfortunately, it seems that the approach doesn't work well with default values (regardless of where the default value is placed). Following the advi ...

The specified type 'IterableIterator<number>' does not belong to either an array type or a string type

Encountering an error while attempting to generate a dynamic range of numbers. Error: Type 'IterableIterator<number>' is not recognized as an array or string type. Use the compiler option '--downlevelIteration' to enable iteratio ...

Send empty object using FormBuilder

When retrieving an object from a backend API service like this: data: {firstName:'pepe',lastName:'test', address = {street: 'Cervantes', city:'Villajoyosa'} } or data: {firstName:'pepe',lastName:'test ...

The property 'class' is required for ".builders['browser']"

Upon successfully installing the dependencies using npm install, I encountered an error while attempting to run the server: Schema validation failed with the following errors: Data path ".builders['browser']" should have required property ' ...

Leveraging async pipe along with ngIf

Given the status property defined and initialized as shown below: public status:Promise<String>; constructor() { this.status = this.getStatus(); } public getStatus():Promise<String>{ return new Promise((resolve,reject)=>{ ...

Leveraging WebStorm's TypeScript support in conjunction with node_modules

Attempting to set up a TypeScript project in WebStorm to import a Node.js module has been a struggle. I made sure to download the necessary TypeScript definition in settings and specified --module commonjs in the compiler settings. However, I keep running ...

Achieving text alignment with icons in Angular

I'm having trouble aligning my text with the icon next to it despite trying to adjust margins. I would really appreciate any help or suggestions on how to resolve this issue. <div class="notification" [ngClass]="{'no ...

Allowing Cross-Origin requests in Spring BootLet's configure the

Every time I attempt to communicate with my backend using my Angular client, I encounter a common error message when trying to perform POST, PUT, and DELETE requests: Access to XMLHttpRequest at 'http://localhost:8087/categories' from origin &ap ...

Changing the global type in TypeScript

Currently, I am incorporating two third-party TypeScript libraries into my project. Interestingly, both of these libraries expose a global variable with the same name through the Window interface. However, they offer different methods for interacting with ...

Confusing generic function overload in TypeScript

During my exploration of TypeScript, I came across an unusual situation. function concat5<T>(strs: T, strs2: T): T; function concat5(strs: string, strs2: string) { return strs + strs2; } concat5(123, 12); concat5({a:1}, {b:2}); Upon reviewing ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

Creating a custom directive in Angular 2 that restricts input to text only

I have recently created a directive that specifically allows only numbers by using key codes. However, I've noticed that when I try to copy and paste text into the text box, it accepts the input but does not display it. Is there a way to utilize &apo ...

What is the best way to apply CSS to a mat-row element only when it is being hovered over?

I have a table with rows where a specific condition triggers a light red background color for each row. On hover, the background changes to light gray for all rows. However, I need the special rows (already colored light red) to have a deeper shade of red ...