Oops! There was an unexpected error in the authGuard: [object Object] was not caught as expected

I've been working on implementing authGuard in my app, but I keep encountering an error.

Below is the guard implementation:

canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    /**
     * Returning an observable of type boolean is the correct way to handle canActivate that needs to wait for an observable result.
     */
    // 1. Select the authConfig from the store
    return this.getAuthentication()
      .pipe(
        // 2. Take the first instance.
        take(1),
        // 3. Map the observable to an observable of type boolean
        // !! turns the value into a boolean
        map((auth: AuthConfig) => !!(auth && auth.success === true)),
        // 4. If not authenticated then redirect the user.
        tap((auth: boolean) => this.redirectUserIfUnauthenticated(auth, this.getRedirectUrl(route))),
        // Catch any errors and handle them.
        catchError((...args) => this.handleError.apply(this, args))
      )
}

This is the getAuthentication function:

private getAuthentication(): Observable<AuthConfig> {
    return zip(
      this.store.select(ngrxTypes.authConfig),
      this.store.select(ngrxTypes.optionsConfig)
    ).pipe(
      mergeMap((configurations: [AuthConfig, OptionsConfig]) => this.getAuthenticationStatus(configurations)),
      mergeMap((authConfig: AuthConfig) => this.setAuthenticationStatus(authConfig))
    );
}

Here's where the HTTP get method is performed:

private getAuthenticationStatus([auth, config]: [AuthConfig, OptionsConfig]): Observable<AuthConfig> {
    if (auth) {
      return this.store.select(ngrxTypes.authConfig);
    } else {
      const token = this.storageService.getCookie('token');
      const apiUrl = `${environment.user_profile_domain_url || config.user_profile_domain_url}/widgets/api/auth`;
      if (config && token) {
        return this.http.get(apiUrl, this.storageService.getHeader('Bearer', token))
          .map(login => login.json())
      } else {
        this.store.dispatch(this.authActions.setAuthConfig({success: false}));
        return this.store.select(ngrxTypes.authConfig);
      }
    }
}

Despite following the process, I consistently face this error and I'm unsure of the reason behind it.

https://i.sstatic.net/oCa4U.png

Answer №1

There seems to be a confusion about the workings of Promises and how to effectively manage errors within them.

In the code snippet provided, upon receiving a response (specifically a 401 error), you handle it in the "catch" block. However, when the condition specified by the if statement is met (i.e., receiving a 401 error), you throw another error that goes unhandled, as there is no subsequent catch block to address it. Consequently, this results in leaving an error unresolved within a promise.

Your intention might have been to throw an error (in case of a 401 response) for the calling code to capture, but instead, you are throwing it within the promise itself, causing the promise to fail due to the unhandled error.

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

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

Transform the `PascalCase` format into `strictCamelCase` in TypeScript type conversion

By utilizing the built-in Uncapitalize<S> function, you can easily convert a string like FooBar to fooBar: const fooBar: Uncapitalize<'FooBar'> = 'fooBar'; However, this method proves inadequate when dealing with class name ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

There seems to be no clear reason as to why the Angular Service is showing

In my DataService component, I have defined two methods - one to read from a file using the cordova-file-plugin and the other to write to it. Initially, it was using the in-mem-web-api, which worked perfectly fine. However, I made some changes to switch th ...

Developing personalized middleware definition in TypeScript for Express

I have been struggling to define custom middleware for our application. I am using [email protected] and [email protected]. Most examples of typing middleware do not involve adding anything to the req or res arguments, but in our case, we need to modify ...

Exploring the Applications of Directives in Multiple Modules within Angular 2

When I declare the directive in two modules, I get an error that says Type PermissionDirective is part of the declarations of 2 modules. However, when I declare it in only one module, I receive an error stating Can't bind to 'isPermission' s ...

Collaborate on a component used in multiple modules

In my application, there are two modules: employer and landing. I have created a component in the landing module that I want to share with the employer module. To achieve this, I declared the component in the app.module.ts file of the parent module and use ...

Executing unit tests in Angular - launch Chrome upon successful build completion (which may take a while)

There are instances where the Angular app takes longer than the default 2-minute timeout for Chrome started by Karma to capture the content. Is there a method to compel Karma to launch Chrome after the build is completed? In my package.json: { "depende ...

I recently updated Angular Cli and now my app is searching for node_modules in a different location. Is there a way for me to revert it

Current Versions. @angular/cli: 1.4.2 node: 6.10.0 os: linux x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @angular/compiler-cli: 4.3.6 @angular/core: 4.3.6 @angular/forms: 4.3.6 @angular/http: 4.3.6 @angular/platform-brow ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

Intercepting HTTP requests in Angular, but not making any changes to the

Working on Angular 13, I am trying to attach a JWT token to the headers in order to access a restricted route on the backend. However, after inspecting the backend, it seems that the JwtInterceptor is not modifying the HTTP request headers. I have included ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

``What is the process for retrieving an object array that has been stored in a session using

I have a new class definition: class ProductDetails { name!: string; price!: number; } I keep an array of these objects in the local storage like this: productList: Array<ProductDetails> = []; ... ... localStorage.setItem("CurrentProducts ...

Receiving an error with React Proptypes when using the union type Breakpoint

Struggling to assign the correct proptype to the material-ui Breakpoint type. The breakpoint values are: export type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl'; In my App.tsx file, I have the following ...