Reputation: 1746
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
Upvotes: 1
Views: 3986
Reputation: 1870
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
Upvotes: 7