如何告诉Angular在遇到异常时不阻止整个应用程序?
我不确定它是否可能,因为谷歌没有启发我.但它似乎对任何单页Web应用程序都至关重要.
Angular是快速的,但只要遇到异常并抛出错误,整个应用程序就会变得无法响应.
我知道在Javascript中
try {
doSomething();
}
catch(err) {
handleErrors(err);
}
Run Code Online (Sandbox Code Playgroud)
可能会解决问题.
但我只想知道是否有任何Angular特定解决方案或解决方法?
Asa*_*nel 14
在角度2最终版本上,您可以实现自定义ErrorHandler.
import {NgModule, ErrorHandler} from '@angular/core';
class MyErrorHandler implements ErrorHandler {
handleError(error) {
// do something with the exception
}
}
@NgModule({
providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
})
class MyModule {}
Run Code Online (Sandbox Code Playgroud)
更新2.0.0 RC.6从更名ExceptionHandler到ErrorHandler和call到handleError
@Injectable()
class MyErrorHandler implements ErrorHandler {
handleError(error) {
// do something with the exception
}
}
@NgModule({
directives: [MyApp],
providers: [
{provide: ErrorHandler, useClass: MyErrorHandler}
]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
另见https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html
原版的
实现自定义异常处理程序https://angular.io/docs/ts/latest/api/core/ExceptionHandler-class.html
@Injectable()
class MyExceptionHandler implements ExceptionHandler {
call(error, stackTrace = null, reason = null) {
// do something with the exception
}
}
@NgModule({
directives: [MyApp],
providers: [
{provide: ExceptionHandler, useClass: MyExceptionHandler}
]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
另见https://github.com/angular/angular/issues/6865和https://github.com/angular/angular/issues/6565
我没有尝试过自己,如果这允许应用程序在异常后继续,但我认为值得一试.至少应该可以自动重新加载页面.
一般情况下,当有办法恢复时,应尽可能地处理异常.
| 归档时间: |
|
| 查看次数: |
9658 次 |
| 最近记录: |