Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common error handling methods in Angular

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the commonly used error handling methods in Angular". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the common error handling methods in Angular.

What is Angular?

Angualr is an open source web front-end framework from Google, born in 2009, created by Misko Hevery and others, and later acquired by Google. Is an excellent front-end JS framework, has been used in a number of Google products.

AngularJS is based on declarative programming mode so that users can develop based on business logic. The framework is based on HTML content filling and bidirectional data binding to complete the automatic data synchronization mechanism. Finally, the enhanced DOM operation of AngularJS enhances testability.

Try/catch

The most familiar way is to add try/catch blocks to the code, and if an error occurs in try, it will be caught and the script will continue to execute. However, as the size of the application grows, this approach will become unmanageable.

ErrorHandler

Angular provides a default ErrorHandler to print error messages to the console, so you can intercept this default behavior to add custom processing logic, so try to write an error handling class:

Import {ErrorHandler, Injectable} from "@ angular/core"; import {HttpErrorResponse} from "@ angular/common/http"; @ Injectable () export class ErrorsHandler implements ErrorHandler {handleError (error: Error | HttpErrorResponse) {if (! navigator.onLine) {console.error ("Browser Offline!");} else {if (error instanceof HttpErrorResponse) {if (! navigator.onLine) {console.error ("Browser Offline!") } else {/ / Handle Http Error (4xx, 5xx, ect.) Console.error ("Http Error!");}} else {/ / Handle Client Error (Angular Error, ReferenceError...) Console.error ("Client Error!");} console.error (error);}

Usually create a shared directory shared under app and put this file in the providers folder

Now we need to change the default behavior of the application to use our custom class instead of ErrorHandler. Modify the app.module.ts file, import ErrorHandler from @ angular/core, and add providers to the @ NgModule module as follows:

Import {NgModule, ErrorHandler} from "@ angular/core"; import {BrowserModule} from "@ angular/platform-browser"; import {FormsModule} from "@ angular/forms"; / / Providersimport {ErrorsHandler} from ". / shared/providers/error-handler"; import {AppComponent} from ". / app.component"; @ NgModule ({imports: [BrowserModule, FormsModule], declarations: [AppComponent], providers: [{provide: ErrorHandler, useClass: ErrorsHandler}], bootstrap: [AppComponent]}) export class AppModule {} HttpInterceptor

HttpInterceptor provides a way to intercept HTTP requests / responses that can be handled before they are delivered. For example, you can retry the HTTP request several times before throwing an error. In this way, timeouts can be handled gracefully without throwing errors.

You can also check the status of the error before throwing it, and using the interceptor, you can check the 401 status error code and redirect the user to the login page.

Import {Injectable} from "@ angular/core"; import {HttpEvent, HttpRequest, HttpHandler, HttpInterceptor, HttpErrorResponse} from "@ angular/common/http"; import {Observable, throwError} from "rxjs"; import {retry, catchError} from "rxjs/operators" @ Injectable () export class HttpsInterceptor implements HttpInterceptor {intercept (request: HttpRequest, next: HttpHandler): Observable {return next.handle (request) .pipe (retry (1), catchError ((error: HttpErrorResponse) = > {if (error.status = 401) {/ / Jump to login page} else {return throwError (error);}});}}

Also need to add to app.module.ts

Import {NgModule, ErrorHandler} from "@ angular/core"; import {HTTP_INTERCEPTORS} from "@ angular/common/http"; import {BrowserModule} from "@ angular/platform-browser"; import {FormsModule} from "@ angular/forms"; / / Providersimport {ErrorsHandler} from ". / shared/providers/error-handler"; import {HttpsInterceptor} from ". / shared/providers/http-interceptor"; import {AppComponent} from ". / app.component" @ NgModule ({imports: [BrowserModule, FormsModule], declarations: [AppComponent], providers: [{provide: ErrorHandler, useClass: ErrorsHandler}, {provide: HTTP_INTERCEPTORS, useClass: HttpsInterceptor, multi: true}], bootstrap: [AppComponent]}) export class AppModule {}

Multiple providers are used to create extensible services, where the system comes with some default providers, and other providers can be registered. A combination of default providers and other providers will be used to drive the behavior of the system.

Notifications

Printing error logs on the console is very friendly for developers, but for users, it needs a more friendly way to tell when these errors occur from GUI. Depending on the type of error, two components are recommended: Snackbar and Dialog

Snackbar: recommended for simple prompts, such as missing required fields in the form or notifying the user of foreseeable errors (invalid email, long user name, etc.).

Dialog: this is recommended when there are unknown server-side or client-side errors; in this way, you can display more descriptions, even call-to-action, such as allowing users to enter their e-mails to track errors.

Add a service to the shared folder to handle all notifications, create a new services folder, and create a file: notification.service.ts, as follows:

Import {Injectable} from "@ angular/core"; import {MatSnackBar} from "@ angular/material/snack-bar"; @ Injectable ({providedIn: "root"}) export class NotificationService {constructor (public snackBar: MatSnackBar) {} showError (message: string) {this.snackBar.open (message, "Close", {panelClass: ["error"]});}}

Update error-handler.ts and add NotificationService:

Import {ErrorHandler, Injectable, Injector} from "@ angular/core"; import {HttpErrorResponse} from "@ angular/common/http"; / / Servicesimport {NotificationService} from ".. / services/notification.service"; @ Injectable () export class ErrorsHandler implements ErrorHandler {/ / Error handling needs to be loaded first. Use Injector to manually inject the service constructor (private injector: Injector) {} handleError (error: Error | HttpErrorResponse) {const notifier = this.injector.get (NotificationService) If (! navigator.onLine) {/ / console.error ("Browser Offline!"); notifier.showError ("Browser Offline!");} else {if (error instanceof HttpErrorResponse) {if (! navigator.onLine) {/ / console.error ("Browser Offline!"); notifier.showError (error.message) } else {/ / Handle Http Error (4xx, 5xx, ect.) / / console.error ("Http Error!"); notifier.showError ("Http Error:" + error.message);}} else {/ / Handle Client Error (Angular Error, ReferenceError...) / / console.error ("Client Error!"); notifier.showError (error.message) } console.error (error);}}

If you throw an error in a component, you can see a good snackbar message:

Log and error tracking

Of course, users cannot be expected to report every bug to, and once deployed in a production environment, they will not be able to see any console logs. Therefore, you need back-end services that can log errors and custom logic to write to the database or use existing solutions such as Rollbar, Sentry, Bugsnag.

Next, create a simple error tracking service and create a logging.service.ts:

Import {Injectable} from "@ angular/core"; import {HttpErrorResponse} from "@ angular/common/http"; @ Injectable ({providedIn: "root"}) export class LoggingService {constructor () {} logError (error: Error | HttpErrorResponse) {/ / This will be replaced with logging to either Rollbar, Sentry, Bugsnag, ect. If (error instanceof HttpErrorResponse) {console.error (error);} else {console.error (error);}

Add the service to the error-handler.ts:

Import {ErrorHandler, Injectable, Injector} from "@ angular/core"; import {HttpErrorResponse} from "@ angular/common/http"; / Servicesimport {NotificationService} from ".. / services/notification.service"; import {LoggingService} from ".. / services/logging.service"; @ Injectable () export class ErrorsHandler implements ErrorHandler {/ / Error handling needs to be loaded first, use Injector to manually inject the service constructor (private injector: Injector) {} handleError (error: Error | HttpErrorResponse) {const notifier = this.injector.get (NotificationService) Const logger = this.injector.get (LoggingService); if (! navigator.onLine) {/ / console.error ("Browser Offline!"); notifier.showError ("Browser Offline!");} else {if (error instanceof HttpErrorResponse) {if (! navigator.onLine) {/ / console.error ("Browser Offline!"); notifier.showError (error.message) } else {/ / Handle Http Error (4xx, 5xx, ect.) / / console.error ("Http Error!"); notifier.showError ("Http Error:" + error.message);}} else {/ / Handle Client Error (Angular Error, ReferenceError...) / / console.error ("Client Error!"); notifier.showError (error.message) } / / console.error (error); logger.logError (error);} at this point, I believe you have a deeper understanding of "what are the common error handling methods in Angular". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report