Detailed explanation of how Angular handles unexpected exception errors

Detailed explanation of how Angular handles unexpected exception errors

Written in front

No matter how well the code is written, it is impossible to fully handle all possible exceptions, especially for applications in production environments, where a large portion of data comes from users and remote locations, and it is difficult to ensure that all data is generated as specified by the program. In fact, unless a tester discovers it or a customer reports it, there is no way to know about it. Therefore, it is very important to report the unknown exceptions generated by the application.

Angular also provides global exception management by default. When an exception occurs, it will be thrown to the Console console. If you are using NG-ZORRO, you may often encounter exception messages that ICON is not loaded. This is also a type of exception message:

core.js:5980 ERROR Error: [@ant-design/icons-angular]:the icon setting-o does not exist or is not registered.
 at IconNotFoundError (ant-design-icons-angular.js:94)
 at MapSubscriber.project (ant-design-icons-angular.js:222)
 at MapSubscriber._next (map.js:29)
 at MapSubscriber.next (Subscriber.js:49)
 at RefCountSubscriber._next (Subscriber.js:72)
 at RefCountSubscriber.next (Subscriber.js:49)
 at Subject.next (Subject.js:39)
 at ConnectableSubscriber._next (Subscriber.js:72)
 at ConnectableSubscriber.next (Subscriber.js:49)
 at CatchSubscriber.notifyNext (innerSubscribe.js:42)

Angular manages exception messages uniformly through ErrorHandler, and you only need to override the handleError method and reprocess the exception message.

ErrorHandler

First create a custom-error-handler.ts file:

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class CustomErrorHandler extends ErrorHandler {
 handleError(error: any): void {
 super.handleError(error);
 }
}

CustomErrorHandler can completely obtain the current user data, current exception message object, etc., and allow reporting to the backend through HttpClient.

The following is the documentation site of NG-ALAIN. Since Google Analytics is used for analysis, we only need to forward the exception message to onerror:

import { DOCUMENT } from '@angular/common';
import { ErrorHandler, Inject, Injectable } from '@angular/core';

@Injectable()
export class CustomErrorHandler extends ErrorHandler {
 constructor(@Inject(DOCUMENT) private doc: any) {
 super();
 }

 handleError(error: any): void {
 try {
  super.handleError(error);
 } catch (e) {
  this.reportError(e);
 }
 this.reportError(error);
 }

 private reportError(error: string | Error): void {
 const win = this.doc.defaultView as any;
 if (win && win.onerror) {
  if (typeof error === 'string') {
  win.onerror(error);
  } else {
  win.onerror(error.message, undefined, undefined, undefined, error);
  }
 }
 }
}

Finally, register the CustomErrorHandler in the AppModule :

@NgModule({
 providers:
  { provide: ErrorHandler, useClass: CustomErrorHandler },
 ]
})
export class AppModule { }

in conclusion

In fact, there is another very important task. The files in the production environment are packaged and compressed. In other words, the exception message generated cannot be the same as the actual number of code lines. This requires the support of SourceMap. Of course, the normal production environment will not publish this file, so if you want to get the correct number of rows and columns, you still need to use an intermediate layer and use the source-map module in the back end to parse the real row and column values.

Angular's dependency injection (DI) system allows us to quickly replace some Angular built-in modules, thereby quickly solving some special needs without modifying the business level.

Summarize

This is the end of this article about how Angular handles unexpected exception errors. For more information about how Angular handles unexpected exception errors, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Using Raygun to automatically track exceptions in AngularJS

<<:  React-native sample code to implement the shopping cart sliding deletion effect

>>:  Detailed explanation of asynchronous programming knowledge points in nodejs

Recommend

Example analysis of MySQL startup and connection methods

Table of contents How to start mysqld Method 1: m...

Specific use of Linux dirname command

01. Command Overview dirname - strip non-director...

Implementation of Docker deployment of Tomcat and Web applications

1. Download docker online yum install -y epel-rel...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

VUE+Canvas realizes the whole process of a simple Gobang game

Preface In terms of layout, Gobang is much simple...

HTML+Sass implements HambergurMenu (hamburger menu)

A few days ago, I watched a video of a foreign gu...

Basic ideas and codes for implementing video players in browsers

Table of contents Preface Summary of audio and vi...

MySQL data loss troubleshooting case

Table of contents Preface On-site investigation C...

Example of how to use CSS3 to layout elements around a center point

This article introduces an example of how CSS3 ca...

Tips for turning pixels into comprehensive brand experiences

Editor: This article discusses the role that inte...

Native JS realizes compound motion of various motions

This article shares with you a compound motion im...