Identifying the origin of the error (whether it's from the client or the server) within

I am utilizing ngrx effect for handling user login in my application:

 @Effect()
 authLogin = this.actions$.pipe(
   ofType(LOGIN_START),
   switchMap(() => this.http.post('/user/login')
     .pipe(
       catchError(
         (response) => {
           console.log('I want to identify the source of error here:', response instanceof HttpErrorResponse)
           return of(/* (...) */)
         }
       ),
     )
   ),
 )

Even though I tried checking the instance of 'response' object, it always turns out to be of type 'HttpErrorResponse'. Whether it's a HTTP error like 422 or a client-side error like ERR_INTERNET_DISCONNECTED, the 'response' object is consistently of type 'HttpErrorResponse'.

Answer №1

If you're looking for ways to establish internet connectivity, consider utilizing the Navigator Object, which contains valuable information about the browser.

catchError((error: HttpErrorResponse) => {
 if (!navigator.onLine) {
      console.error('Unable to connect to the internet', 'Network');
 } else if (401 === error.status) {

 } else if (400 === error.status) {

 }
 ...
})

Answer №2

If you encounter errors that you are unable to handle, it is recommended to place them in the else block for logging purposes or any other specific action. See the example below:

catchError((response: HttpErrorResponse) => {
        if (response.status === 401) {
            //do something
        } else if (response.status === 404) {
            //do something
        } else if (response.status === 403) {
            //do something
        } else if (response.status === 500) {
            //do something            
        } else {
            console.log(response.message, response.statusText);
        }
        return throwError(response);
    }
)

By using this approach, you can effectively handle various types of errors, such as network issues, through the else block.

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

Binding an event specifically for keypress action

Angular allows me to use <input (keyup.enter)"onEnter($event)"> to capture the Enter key being pressed by the user. Similarly, I can also detect other keys such as esc, space, and shift. But how can I detect when the user presses shift + up? Is th ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

Can the output object from an angular form validator be obtained and utilized?

As per the documentation, The validator is capable of returning an object {[key: string]: any} or null This implies that it can return an object (for any) which includes detailed information about what went wrong during validation. For example: function ...

Dealing with Angular package.json and unresolved peer dependencies

As I embark on the journey of developing an Angular project using CLI, I am also exploring additional components like angular handsontable and primeng. Amidst this exploration, a wave of confusion hit me when I attempted to check the versions of various pa ...

Display a unique element depending on the path of the Dynamic Angular Routing

Here are the routes I am working with: /dashboard /dashboard/view-all /dashboard/edit/:id One specific issue I've encountered is related to showing/hiding the EditComponent based on the dynamic router. Typically, I can show/hide Angular components ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...

"Angular SwtAlert2: The Ultimate Multi-Selection Tool

I am trying to integrate the ng-select directive into SweetAlert2, but the code snippet below is not working as expected: const { value: formValues } = await swal.fire({ title: 'Multiple inputs', html: '<ng-select id=" ...

When I tap on a text element, place the cursor in the input field

I want to set the focus to an input field when I click on a specific piece of text within the same page. What is the most efficient way to achieve this? I already have a function attached to the text element. Below is the code snippet that I am working wit ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Angular Universal does not fully render on the server side

Currently, my project involves integrating Angular 4 with Angular Universal and Knockout. The main objective is to have the Angular application generate HTML on the server side for SEO purposes. As part of this process, I need to utilize KnockoutJs to bin ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Exploring Angular's Animation Feature for HTML Element Movement

I'm currently using @angular/animations module to animate HTML objects and I want to move an object when a button is clicked. For example: * The object initially has top: 800px, left: 800px * Clicking the 'W' button should move the obje ...

Angular2 - Retrieve data in XLS format from RestService并下载

I am looking to create a web service using Apache POI to generate an Excel file (xls, xlsx). Below is the snippet of code I have put together: @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportXlsx(HttpServletResponse respon ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...

In Typescript, a function that is declared with a type other than 'void' or 'any' is required to have a return value

I'm a beginner in Angular2/Typescript and I am encountering an error while trying to compile my project: An error is showing: A function that has a declared type other than 'void' or 'any' must return a value. Here is the code sn ...