繁体   English   中英

Angular2中的ErrorHandler

[英]ErrorHandler in Angular2

我有一个关于新类ErrorHandler的问题(包含在RC.6中)。

我从官方文档中做了一些例子: 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 {}

编辑app.module文件后

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

现在MyErrorHandler捕获错误:

throw new Error("my test error");

但它没有捕获http错误,如:“GET http://example.com/rest/user 401(Unauthorized)”。 任何人都可以解释一下吗?

提前致谢!

要处理HTTP错误,请将.catch()运算符添加到observable

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

当http调用返回4-500s中的状态代码时,将调用该函数。 从那里你可以随意抛出错误

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

强烈地说401(或其他任何事情)并不是一个错误。 它只是一个HTTP返回码。 如果此类代码破坏了您的应用程序功能,您需要自己处理它。 但是有一些真正的错误,比如连接错误,我也想知道如何处理。 这是我的问题: Angular 2 http服务。 获取详细的错误信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM