简体   繁体   中英

Angular 2 custom HTTP error handling using component

This is what I have so far:

@Component({
  selector: 'error-handler',
  templateUrl: 'error-handler.html'
})
export class ErrorHandlerComponent extends ErrorHandler {

  text: string;

  constructor() {
    super();
  }

  handleError(error: HttpErrorResponse) {
    console.log("ErrorHandlerComponent, error.status: ", error.status);
    this.text = error.message;
  }
}

But my the flow doesn't go into handleError, I get the below error:

polyfills.js:3 Uncaught Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …}

Your ErrorHandler needs to be an @Injectable , not a @Component . It doesn't have a view associated with it - it's a service. It should look something like this:

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super();
  }

  handleError(error) {
    // do whatever

    super.handleError(error);
  }
}

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