Dealing with the "error" parameter in JSON in Angular and Ionic

I am currently working with TypeScript and Angular 5.0. I have defined the structure of my backend response in the following interface:

export interface JSONResponse {
  error?: {
    code: number,
    message: string
  };
  data?: {};
}

The method in my service to retrieve data from the server is as follows:

httpGet(url: string, httpParams: HttpParams) {
  return new Promise((resolve, reject) => {
    this.http.get<LoginResponse>(url, {params: httpParams})
      .subscribe(res => {
        resolve(res.data);
      }, err => {
        // handle HTTP GET errors here
        console.log(err);
      });
  });
}

This is how the component utilizes the service to display the template:

buttonClicked(event) {
  this.myService.httpGet('myAPIurl', someRequestParams)
    .then((data) => {
      this.myData = data;
    }, (err) => {
      console.log(err);
    });
}

Where should I implement the logic for checking errors in the response from the backend?

In other words, if the property data exists, the response was successful and I can process the data accordingly. If the property error exists, I need to inform the user about the error with the corresponding code/message.

Answer №1

To achieve a more general approach, you can utilize the IonicErrorHandler.

By using the IonicErrorHandler, you can intercept default Console error handling and showcase runtime errors as an overlay when employing Ionic's Dev Build Server.

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicErrorHandler } from 'ionic-angular';

@NgModule({
  providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler }]
})
class AppModule {}

If you desire to customize it, you have the option to do so.

class MyErrorHandler implements ErrorHandler {
  handleError(err: any): void {
    // perform actions on the error
  }
}

NgModule({
  providers: [{ provide: ErrorHandler, useClass: MyErrorHandler }]
})
class AppModule {}

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

Utilizing useClass in Angular's APP_INITIALIZER

Before my application starts up, I require some API data and am currently handling it with APP_INITIALIZER and useFactory. However, I aim to enhance the structure by separating all the code from app.module.ts: app.module.ts import { NgModule} from '@ ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

What is the correct way to exclude and remove a portion of the value within an object using TypeScript?

The function useHider was created to conceal specific values from an object with the correct type. For example, using const res = useHider({ id: 1, title: "hi"}, "id"), will result in { title: "hi" } being returned. Attempting ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Combining normal imports with top-level await: A guide

Is it possible to simultaneously use imports (import x from y) and top-level awaits with ts-node? I encountered an issue where changing my tsconfig.compilerOptions.module to es2017 or higher, as required by top-level awaits, resulted in the following error ...

Leverage async and await features in TypeScript aiming at ES5 compatibility

Currently working on a TypeScript project that is set to target ES5, I am exploring the feasibility of incorporating async/await functionality. Syntactically, the TypeScript compiler is able to transpile the code without issues. However, it has come to my ...

What is the process of assigning attribute values conditionally in Angular 2?

I'm currently exploring Angular 2 and facing a challenge with a basic material input tag. I want to dynamically set its value based on a condition. <md-input value="dataSelected ? {{selectedDataName}} : ''"></md-input> I attemp ...

Create a single datetime object in Ionic (Angular) by merging the date and time into a combined string format

I have a string in an ionic project that contains both a date and time, and I need to merge them into a single datetime object for sending it to the server const date = "Fri Jan 07 2022 13:15:40 GMT+0530 (India Standard Time)"; const time = " ...

The parameter failed to initialize causing the HTTP service to fire prematurely

In my project, I am utilizing Angular 10. Within the ngOnInit function, I have nested HTTP calls structured like this: ngOnInit(): void { let communetyid; this.route.data.subscribe(data => { this.route.params.subscribe(params => { ...

Join our exclusive membership program for table enthusiasts

I'm facing a situation where I have two specific questions: 1) Why is my method returning the same object twice when I use console.log? 2) Why does my method not work when I add my filter? The console.log shows the object, but nothing appears in my ...

Guide to automatically installing @types for all node modules

As a newcomer to Typescript and NodeJs, I have been experiencing errors when mentioning node modules in my package.json file and trying to import them. The error messages I always encounter are as follows: Could not find a declaration file for module &apos ...

Is a loading animation needed to reload once the content is fully loaded?

Currently, I am utilizing Ionic to create a basic tab application that fetches information from an external source (specifically parse). For the most part, everything runs smoothly. However, on occasion, I encounter situations where clicking on a view rend ...

Async await causing failure in change detection

1. Displaying a loading animation while waiting for API data to resolve 2. Once the API response is received, turning off the loader flag and attempting to access the div element within the flag 3. The flag value is updated but the DOM is not refreshed, le ...

Errors detected while attempting to install dependencies using pnpm: modules unspecified

I recently decided to experiment with using pnpm instead of npm for my new projects, but I've encountered an issue. Let's take my nuxt project as an example. First, I set up my project using the command: pnpx nuxi init my-project Then, I insta ...

The Power of Jinja 2: Extracting Values from Lists

When I post object['userinfo'] to Jinja2 HTML, it displays the information like this. [{ 'enemies':[ ], 'url':'URL', 'friends':[ { 'area':2, ...

Decoding arrays of JSON data

Receiving "chunked" data (json arrays) on the front-end via "xhr" (onprogress). Handling delayed chunks is easy - just remember response length and offset. The challenge comes when multiple "chunked" responses arrive simultaneously, resulting in an unpars ...

Transmitting various parameters with XMLHttpRequest and Windows Communication Foundation (WCF

My goal is to pass multiple parameters to a WCF service, where the server side logs incoming data. I can see errors 1 and 2 being logged, but not 3 and 4. I attempted debugging to step through the code, but the client-side javascript call isn't trigge ...

Challenges associated with adding information to FormData in an Angular Net 5 Application

I'm currently working on developing an application using Angular 11 and .NET 5 and am facing some challenges while trying to implement the file upload feature. I have successfully managed to send pictures to the server, but I'm encountering issue ...

Ember and Mongoose are not providing the expected record returns

Currently facing an issue with Ember and models. My goal is to return JSON from a Mongoose API using Express. The problem lies in the fact that the route successfully returns the JSON, but upon trying to retrieve it on the front end (Ember), it appears as ...