How to log all possible console errors occurring in Angular application on a client's side?
If you wish to catch and log all the errors (not only HTTP nature ones) in your Angular application I'd propose you the way that Sentry and other bug trackers use.
Angular has an ErrorHandler
class which provides a hook for centralized exception handling.
So your task would be to create your own error handler. I usually do it like this:
import {ErrorHandler, Injectable} from '@angular/core';
import {LoggerService} from './some/logger.service';
@Injectable()
export class CustomErrorHandlerService extends ErrorHandler {
constructor(private logger: LoggerService) {
super();
}
handleError(error) {
// Here you can provide whatever logging you want
this.logger.logError(error);
super.handleError(error);
}
}
The next step is to use your error handler by means of Dependency Injection. Just add it in your AppModule
like this:
import {CustomErrorHandlerService} from '~/app/_services/custom-error-handler.service';
@NgModule({
imports: [...],
declarations: [...],
providers: [
...
{provide: ErrorHandler, useClass: CustomErrorHandlerService},
],
bootstrap: [AppComponent]
})
That's it. The key feature of such implementation is that this service handles all possible errors, appearing in your application (just like you ask in your question) including HTTP errors and others.
Please, leave your comments if you have any additional questions.