加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2中的ErrorHandler

发布时间:2020-12-17 07:19:49 所属栏目:安全 来源:网络整理
导读:我有一个关于新类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
我有一个关于新类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(未经授权)”.
任何人都可以解释一下吗?

提前致谢!

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读