Ego*_*tov 7 error-handling angular2-ngmodel angular
我有一个关于新类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 {}
Run Code Online (Sandbox Code Playgroud)
编辑app.module文件后
import {MyErrorHandler} from "./error.module";
import {MyErrorModule } from "./error.module";
..
@NgModule({
imports: [
MyErrorModule
....
],
...
providers: [MyErrorHandler]
....
Run Code Online (Sandbox Code Playgroud)
现在MyErrorHandler捕获错误:
throw new Error("my test error");
Run Code Online (Sandbox Code Playgroud)
但它没有捕获http错误,如:"GET http://example.com/rest/user 401(Unauthorized)".任何人都可以解释一下吗?
提前致谢!
Bee*_*ice 10
要处理HTTP错误,请.catch()
向observable 添加运算符
return this.http.get(url,options)
.catch((res)=>this.handleHTTPError(res));
Run Code Online (Sandbox Code Playgroud)
当http调用返回4-500s中的状态代码时,将调用该函数.从那里你可以随意抛出错误
handleHTTPError(res:Response){
throw new Error("HTTP error: "+res.statusText+" ("+res.status+")");
}
Run Code Online (Sandbox Code Playgroud)
强烈地说401(或其他任何事情)并不是一个错误.它只是一个HTTP返回码.如果此类代码破坏了您的应用程序功能,您需要自己处理它.但是有一些真正的错误,比如连接错误,我也想知道如何处理.这是我的问题: Angular 2 http服务.获取详细的错误信息
归档时间: |
|
查看次数: |
8172 次 |
最近记录: |