【问题标题】:ErrorHandler in Angular2Angular2中的错误处理程序
【发布时间】:2017-01-21 18:31:30
【问题描述】:

我有一个关于新类 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)”。 谁能给我解释一下?

提前致谢!

【问题讨论】:

    标签: angular error-handling angular2-ngmodel


    【解决方案1】:

    严格来说 401(或其他任何东西)并不完全是错误。它只是一个 HTTP 返回码。如果此类代码破坏了您的应用程序功能,您需要自己处理。 但是有一些真正的错误,比如连接错误,我也想知道如何处理。 这是我的问题: Angular 2 http service. Get detailed error information

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 有没有办法使用自定义错误句柄/服务来处理 HTTP 错误?我问的原因是因为我有很多服务,其中很多都有 HTTP 调用。我希望能够声明一个handletHTTPError 方法
      • 所以最好让错误拦截器跟踪 http 错误。它还可以跟踪服务的正常错误。
      猜你喜欢
      • 2016-08-10
      • 2016-08-18
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多