[英]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.