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

Five ways to traverse JavaScript arrays

Table of contents 1. for loop: basic and simple 2...

Implementation of react loop data (list)

First, let's simulate the data coming from th...

The principles and defects of MySQL full-text indexing

MySQL full-text index is a special index that gen...

Overview of time configuration under Linux system

1. Time types are divided into: 1. Network time (...

Three BOM objects in JavaScript

Table of contents 1. Location Object 1. URL 2. Pr...

How to configure MySQL master-slave synchronization in Ubuntu 16.04

Preparation 1. The master and slave database vers...

How to build your own Angular component library with DevUI

Table of contents Preface Creating a component li...

XHTML Getting Started Tutorial: XHTML Hyperlinks

It is no exaggeration to say that hyperlinks conne...

Python 3.7 installation tutorial for MacBook

The detailed process of installing python3.7.0 on...

Detailed explanation of the role of brackets in AngularJS

1. The role of brackets 1.1 Square brackets [ ] W...

How to set the page you are viewing to not allow Baidu to save its snapshot

Today, when I searched for a page on Baidu, becaus...

Detailed tutorial on using the Prettier Code plugin in vscode

Why use prettier? In large companies, front-end d...

Various transformation effects of HTML web page switching

<META http-equiv="Page-Enter" CONTENT...