1

I've got the simpliest implementation of Angular's (v2.4.3) custom error handler but still can't log errors. What can be wrong?

app.module.ts

providers: [
    { provide: ErrorHandler, useClass: MyErrorHandler }
]

my-error-handler.ts

import { ErrorHandler, Injectable} from '@angular/core';

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor(private errorHandlerService: ErrorHandlerService) {
    super();
  }

  public handleError(error: any): void {
    console.log('error'); // nothing
  }
}

sample-service.ts (trying to throw error)

  addSomething(data) {
    let bodyString = JSON.stringify(data);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.url + 'expense', bodyString, options)
      .map((res: Response) => res.json())
      .catch(this.handleError);
  }

  private handleError(error: any) {
    console.log(error.json()); // error: { message: 'Some error' }

    return Observable.throw(error.json());
  }

Error throwed in service never get to MyErrorHandler. What could be wrong?

I don't know if that's important but in console I also got something like this:

POST http://path/to/api 422 // logged by zone.js

1 Answer 1

7

change

export class MyErrorHandler extends ErrorHandler {

to

export class MyErrorHandler implements ErrorHandler {

refer to here https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html

And you should also remove the .catch method that short-circuit the error handling

return this.http.post(this.url + 'expense', bodyString, options)
  .map((res: Response) => res.json())
  .catch(this.handleError);      // remove this method call
Sign up to request clarification or add additional context in comments.

5 Comments

I think that's because you have specified another handler using .catch method. Remove it, you should be able to see your custom error handler getting called
Yes, that's it. Thank you! Can you post it as an answer so I can mark it as a solution?
Using extends instead if implements frees you up to be able to inject custom services into you MyErrorHandler class, instead of using private injector: Injector.
Shouldn't you also be able to use extends? My understanding is extends allows you to preserve the default functionality and then add to it (which is what I'd like to know how to do). How can I get this to work with extends?
in my case it is getting called twice, any info ?

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.