1

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.

3
  • What is the issue right now you have? Commented Nov 15, 2017 at 20:33
  • I'm trying to figure out where is the place in the code to perform the JSON parsing, and check whether the data or error field exists or not, and eventually inform in the UI the processed data or the error Commented Nov 15, 2017 at 20:37
  • Why can't you do it here (err) => { console.log(err); in the buttonClicked() event? Commented Nov 15, 2017 at 20:40

1 Answer 1

1

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 {}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.