Angular2:遇到异常/错误后,应用程序崩溃/无响应

Ank*_*ngh 28 angular

如何告诉Angular在遇到异常时不阻止整个应用程序?

我不确定它是否可能,因为谷歌没有启发我.但它似乎对任何单页Web应用程序都至关重要.

Angular是快速的,但只要遇到异常并抛出错误,整个应用程序就会变得无法响应.

我知道在Javascript中

try {
  doSomething();
}
catch(err) {
  handleErrors(err);
}
Run Code Online (Sandbox Code Playgroud)

可能会解决问题.

但我只想知道是否有任何Angular特定解决方案或解决方法?

Asa*_*nel 14

在角度2最终版本上,您可以实现自定义ErrorHandler.

来自Angular文档的示例:

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)


Gün*_*uer 9

更新2.0.0 RC.6从更名ExceptionHandlerErrorHandlercallhandleError

@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/6865https://github.com/angular/angular/issues/6565

我没有尝试过自己,如果这允许应用程序在异常后继续,但我认为值得一试.至少应该可以自动重新加载页面.

一般情况下,当有办法恢复时,应尽可能地处理异常.

  • 我试过并成功地重定向到非容易出错的主页,这比什么都没有好.但我还没有找到一种方法让应用程序即使在异常之后也能保持响应,这通常不是一个好方法,但作为一个后备,它可能会很好. (3认同)