ErrorHandler in Angular2

Egor picture Egor · Sep 14, 2016 · Viewed 8.3k times · Source

I have a question about new class ErrorHandler (was included to RC.6).

I did example from official docs: https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html

import{ErrorHandler} from "@angular/core";
import{NgModule} from "@angular/core";
export class MyErrorHandler implements ErrorHandler {

    call(error: any, stackTrace: any = null, reason: any = null) {
        // do something with the exception
        console.log("do something with the exception");
    }

    // I handle the given error.
    public handleError( error: any ): void {
        console.log("I handle the given error");
    }

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

After I edited my app.module file

import {MyErrorHandler} from "./error.module";
import {MyErrorModule } from "./error.module";
..
@NgModule({
    imports: [
        MyErrorModule
    ....
    ],
    ...
    providers: [MyErrorHandler]
   ....

Now MyErrorHandler catches errors:

throw new Error("my test error");

But it doesn't catch http errors like: "GET http://example.com/rest/user 401 (Unauthorized)". Can anybody explain me it?

Thanks in advance!

Answer

BeetleJuice picture BeetleJuice · Sep 14, 2016

To handle HTTP errors, add a .catch() operator to the observable

return this.http.get(url,options)
    .catch((res)=>this.handleHTTPError(res));

The function will be called when an http call returns status code in the 4-500s. From there you can throw the error as you wish

handleHTTPError(res:Response){
    throw new Error("HTTP error: "+res.statusText+" ("+res.status+")");
}