Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ErrorHandler in Angular2

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!

like image 680
Egor Avatar asked Sep 14 '16 03:09

Egor


2 Answers

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+")");
}
like image 79
BeetleJuice Avatar answered Nov 12 '22 22:11

BeetleJuice


Strongly speaking 401 (or anything else for that matter) is not exactly an error. It's just an HTTP return code. You need to handle it yourself if such code breaks your application functionality. But there are real errors like connection error which I'd also like to know how to handle. Here's my question about it: Angular 2 http service. Get detailed error information

like image 37
rook Avatar answered Nov 12 '22 22:11

rook