The endpoint throws an error, yet the HTTP subscription fails to capture it

My code seems simple enough.

let body = new FormData();
body.set("a", true);
body.set("username", this.user);
body.set("password", this.password);

let headers = new HttpHeaders();
headers.set("Content-Type", 'application/x-www-form-urlencoded')

console.log("about to post");
this.http.post("/endpoint", body, {headers: headers}).subscribe(
    (result) => { console.log("success", result); /*extra code*/},
    (error) => { console.log("error", error); /*extra code*/ },
    () => { console.log("Complete"); /*extra code*/ });

This is a rather straightforward subscription process.

When I make a post request, it returns a 401 unauthorized network request error. The problem lies in the fact that the console output displays

about to post
POST [url] 401 (Unauthorized)
Complete

It doesn't execute the error handling functionality.

In the constructor, http is defined as: private http: HttpClient

Therefore, I am confused about why it fails to trigger the error response. Is there something missing? I checked similar posts like Catching errors in Angular HttpClient which I believed I followed regarding the subscription process.

On successful requests, the success function works fine.

Edit Upon further inspection of the code, I realized that maybe the data or headers were incorrect. So, I made updates accordingly. It seemed that the data being sent appeared incorrect, so I changed it to form data. As I traced through the endpoint until encountering a "throw new Exception('Authorization Error')", the error function was never triggered. Could there be something lacking in how I set up the post request? Perhaps an internal issue caused by improper configuration?

Answer №1

Discover a simulated server call scenario using this interactive playground

A custom 'FakeBackendInterceptor' component intercepts HTTP requests to mimic unauthorized responses specifically for '/protected' endpoint.

The entry point of the application is HelloComponent, initiating authorized and unauthorized calls through get and post services.

If encountered with an error, explore two different approaches by leveraging ErrorInterceptor component or handle 401 responses directly within the service.

Note the imperative order at app.module:

providers:    [ 
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: FakeBackendInterceptor, multi: true },
  ], 

Ensure inclusion of HttpClientModule in imports section:

imports:      [ HttpClientModule, BrowserModule, FormsModule ],

To bypass interceptor, consider this alternative approach:

this.service.post().subscribe(
  (result) => { console.log("success", result); /*additional code*/},
  (error) => { 
    console.log("error", error); /*additional code*/ 
    if (error.status === 401)  {
      console.log("You are not authorized");
    }
  },
  () => { console.log("Complete"); /*additional code*/ })
}

Additionally, a PUT request case tests handling 401 response within the service:

let body = new FormData();
body.set("a", 'true');
body.set("username", 'user');
body.set("password", 'password');

let headers = this.createHeaders();

console.log("calling services unauthorized PUT");
return this.http.put<any>("/protected", body, { headers, observe: "response" }).
pipe(
  map(res => {
  if (res.status === 400 || res.status === 401) {
    throw new Error(res.body.message);
  }
  return res.body;
}));

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

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...

Exploring the benefits of using TypeScript with Angular2 for HTTP

I have a locally stored "region.json" file containing the following data: { "regionId":1, "region":"CAN" }, { "regionId":2, "region":"CEN" } Additionally, I have an "enviroment-app.component.ts" file structured as follows : import {Component, ...

Utilizing Angular 5: Display a Loading Indicator while Searching using Async Pipe

As I work on incorporating a search field with async in Angular 5, I want the loading indicator to appear when the user starts typing in the search box and disappear once the results are fetched. However, following this approach led to the loading indicato ...

Deploying with Angular

My Angular application is functioning well without any errors. However, after deployment, I encounter a 404 error when reloading the page. I anticipate my app to work even after a full reload following deployment. Please see image for more details Any s ...

Creating a Responsive Design for an SVG Circle Divided into Three Equal Parts in an Ionic Mobile App

Seeking assistance with an Ionic mobile app project where I am attempting to divide an SVG circle into three equal parts while focusing on responsive design. I have experimented with using the SVG element, but have encountered challenges in achieving both ...

Mastering the intricacies of Angular bindings through intuition

I am attempting to grasp the concept of distinguishing between square brackets binding <elem [...]="..."><elem> and parentheses binding <elem (...)="..."<elem>. Is there a rule of thumb that can help differentiate between the two? Pe ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

Angular dynamic array implementation

Essentially, I have an API that returns data when a search is performed. I store this data in an array and display it using ngFor in my HTML. However, whenever I attempt a new search, the same function is called but the HTML does not update to show the ne ...

What is the best way to include a routerLink within a ternary operator?

Within my Angular HTML code, I have a ternary condition as shown below: <my-tag [top-position]="find.distance ? find.distance.code : find.volume.code" [rClass]="r.rClass"></my-tag> I am attempting to make the content above ...

During the evaluation of an Angular application, an examination was conducted on the feature where clicking a button would increase a count and show the result in an h2 element

After clicking a button, the count is supposed to increase and the updated count should be displayed on the HTML page using Angular. I have written a test for this scenario using Jasmine + Karma runner, but the expected value is not matching. During testi ...

Exploring Angular Material's Autocomplete feature and staying updated with incoming data changes

https://material.angular.io/components/autocomplete/examples export class AutocompleteAutoActiveFirstOptionExample implements OnInit { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; filtered ...

Error message "Cannot bind to 'name' because it is not a recognized native property" encountered in Ionic icon configuration

Currently, I am developing a mobile app using Ionic 2 and Angular 2. I encountered an issue when trying to use the [name] property in conjunction with Ionic icons and expressions like this: <icon item-right [name]="result.kind ==='song&apo ...

Encountered an issue resolving the dependency while executing npm i

I encountered an issue while trying to run the npm i command: npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a ...

Anticipating outcome in NgRx Effects

Incorporating ngrx-effects into my project has been successful for retrieving data: component dispatches action -> effect triggers http service call -> data is returned from http service -> effect sends data to store through action -> component ...

Error encountered: React Typescript does not support the "any" type in a template literal expression

I have been encountering an issue with my slider component in React Typescript. The error message I keep getting is related to the "Invalid type 'any' of template literal expression" specifically at the const fillWidth variable. I am struggling t ...

Tips for monitoring the loading of data in TypeScript with observers?

One of the methods in my class is responsible for fetching information from the server: public getClassesAndSubjects(school: number, whenDate: string) { this.classService.GetClassesAndSubjects(school, whenDate).subscribe(data => { if (!data.h ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Exploring the World of Angular2's RC.1 Dependency Injection

Currently, I am delving into Angular2, but the challenge lies in the fact that every time I come across a helpful tutorial, it does not align with the latest version of Angular2. Despite this, my current struggle involves attempting to inject a service fr ...