2016-09-14 8 views
7

新しいクラスErrorHandlerについて質問があります(RC.6に含まれています)。ErrorHandler in Angular2

私は公式ドキュメントからの例をした:

throw new Error("my test error"); 

しかし、それはdoesnの:私は

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

今すぐMyErrorHandlerがエラーをキャッチ私のapp.moduleファイルを編集した後 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 {} 

次のようなhttpエラーをキャッチしないでください: "GET http://example.com/rest/user 401 (Unauthorized)」と表示されます。誰でも私にそれを説明できますか?

ありがとうございます!

答えて

5

強く401を話していても、まったく問題ではありません。それは単なるHTTPリターンコードです。そのようなコードがアプリケーションの機能を壊した場合は、それを自分で処理する必要があります。 しかし、接続エラーのような実際のエラーがあります。これは、処理方法も知りたいです。ここ はそれについての私の質問です: Angular 2 http service. Get detailed error information

10

HTTPエラーを処理するには、観察可能な

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

に関数を.catch()演算子を追加するHTTP呼び出しが4-500sでステータスコードを返したときに呼び出されます。そこからあなたが望むようにエラーをスローすることができます

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

カスタムエラー処理/サービスでHTTPエラーを処理する方法はありますか?なぜなら、私は多くのサービスを持っており、多くの人がHTTPコールを持っているからです。私は 'handletHTTPError'メソッドを宣言できるようにしたいと思います – Kosmonaft