ErrorHandler in Angular2

2019-04-06 22:53发布

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!

2条回答
Lonely孤独者°
2楼-- · 2019-04-06 23:21

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+")");
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-04-06 23:25

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

查看更多
登录 后发表回答