Application becomes unresponsive after encountering an exception
How to tell Angular 2 to not block the whole application when it encounters an exception?
I'm not sure if it's even possible, because Google didn't enlighten me on this. But it seems critical to any single page web application.
Whenever Angular 2 encounters an exception and throws an error, the complete application becomes unresponsive.
I know that in JavaScript
try {
doSomething();
}
catch(err) {
handleErrors(err);
}
might solve the problem.
But I just want to know if there is any Angular specific solution or workaround?
On angular 2 final version, you can implement custom ErrorHandler
(Angular 2 docs example):
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 {}
UPDATE:
2.0.0 RC.6 changed the name from ExceptionHandler
to ErrorHandler
and call
to handleError
:
@Injectable()
class MyErrorHandler implements ErrorHandler {
handleError(error) {
// do something with the exception
}
}
@NgModule({
directives: [MyApp],
providers: [
{provide: ErrorHandler, useClass: MyErrorHandler}
]
})
export class AppModule {}
See also this.
ORIGINAL:
Implement a custom exception handler:
@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 {}
See also this and this.
I haven't tried myself if this allows the application to continue after an exception, but I think it's worth a try. At least reloading the page automatically should be possible.
Generally, an exception should be handled as close as possible to the cause when there is a way to recover.