ErrorHandler in Angular2 [英] ErrorHandler in Angular2
问题描述
我从官方文档中做过例如:
https://angular.io/docs/ts/latest/api/core来自@ angular / core的/index/ErrorHandler-class.html
import {ErrorHandler};
import {NgModule} from@ angular / core;
导出类MyErrorHandler实现ErrorHandler {
调用(错误:any,stackTrace:any = null,reason:any = null){
//执行异常
console.log(做某事异常);
}
//我处理给定的错误。
public handleError(error:any):void {
console.log(I handle the given error);
}
}
@NgModule({
providers:[
{
提供:ErrorHandler,
useClass:MyErrorHandler
}
]
})
导出类MyErrorModule {}
importMyErrorHandlerfrom./error.module;
import {MyErrorModule} from./error.module;
..
@NgModule({
imports:[
MyErrorModule
....
],
...
提供者:[MyErrorHandler]
....
现在MyErrorHandler捕获错误: p>
抛出新错误(我的测试错误);
但它没有捕获http错误,如:GET http:/ /example.com/rest/user 401(未经授权)
任何人可以解释一下吗?
提前感谢!
要处理HTTP错误,请将 .catch()
运算符添加到observable
返回this.http.get(url,options)
.catch((res)=> this。 handleHTTPError(res));
当http调用返回4的状态代码时,将调用该函数-500s。从那里你可以按照你的意愿抛出错误
handleHTTPErr或者(res:Response){
throw new Error(HTTP error:+ res.statusText +(+ res.status +));
}
I have a question about new class ErrorHandler (was included to RC.6).
I did example from official docs: 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 {}
After I edited my app.module file
import {MyErrorHandler} from "./error.module";
import {MyErrorModule } from "./error.module";
..
@NgModule({
imports: [
MyErrorModule
....
],
...
providers: [MyErrorHandler]
....
Now MyErrorHandler catches errors:
throw new Error("my test error");
But it doesn't catch http errors like: "GET http://example.com/rest/user 401 (Unauthorized)". Can anybody explain me it?
Thanks in advance!
To handle HTTP errors, add a .catch()
operator to the observable
return this.http.get(url,options)
.catch((res)=>this.handleHTTPError(res));
The function will be called when an http call returns status code in the 4-500s. From there you can throw the error as you wish
handleHTTPError(res:Response){
throw new Error("HTTP error: "+res.statusText+" ("+res.status+")");
}
这篇关于ErrorHandler in Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!