ErrorHandler in Angular2

落爺英雄遲暮 提交于 2019-12-09 16:43:26

问题


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!


回答1:


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+")");
}



回答2:


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



来源:https://stackoverflow.com/questions/39482173/errorhandler-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!