我有一个关于新类 ErrorHandler (包含在 RC.6 中)的问题。
我从官方文档中做了示例:https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html 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 错误,例如:“GEThttp://example.com/rest/user http://example.com/rest/user401(未经授权)”。
有人能给我解释一下吗?
提前致谢!
要处理 HTTP 错误,请添加.catch()
可观察值的运算符
return this.http.get(url,options)
.catch((res)=>this.handleHTTPError(res));
当 http 调用返回 4-500 秒内的状态代码时,将调用该函数。从那里你可以根据需要抛出错误
handleHTTPError(res:Response){
throw new Error("HTTP error: "+res.statusText+" ("+res.status+")");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)