简体   繁体   中英

Angular / Ionic - Handle JSON “error” property

I'm using TypeScript, Angular 5.0. My backend response is summarized in this interface:

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

The function in my service to get the data from the server is:

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 related errors here
        console.log(err);
      });
  });
}

And then the component that consume this service to render the template:

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

Where would be the place to handle the error checking of the response from my backend?

That is, if property data is present, the response is successful and do the proper processing of my data; if property error is present, I notify the user with the code/message error.

If you need to do it in a more generic way you can use IonicErrorHandler .

The IonicErrorHandler intercepts the default Console error handling and displays runtime errors as an overlay when using 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 want to customise it you can do that too.

class MyErrorHandler implements ErrorHandler {
  handleError(err: any): void {
    // do something with the error
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM