本篇內(nèi)容主要講解“Angular中處理錯誤的方式是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Angular中處理錯誤的方式是什么”吧!
成都創(chuàng)新互聯(lián)公司專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,服務(wù)器托管,服務(wù)器托管,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
Angualr
是一款來自谷歌的開源的 web 前端框架,誕生于 2009 年,由 Misko Hevery 等人創(chuàng)建,后為 Google 所收購。是一款優(yōu)秀的前端 JS 框架,已經(jīng)被用于 Google 的多款產(chǎn)品當(dāng)中。
AngularJS 是基于聲明式編程模式 是用戶可以基于業(yè)務(wù)邏輯進(jìn)行開發(fā). 該框架基于HTML的內(nèi)容填充并做了雙向數(shù)據(jù)綁定從而完成了自動數(shù)據(jù)同步機(jī)制. 最后, AngularJS 強(qiáng)化的DOM操作增強(qiáng)了可測試性.
最熟悉的的方式,就是在代碼中添加try/catch
塊,在try
中發(fā)生錯誤,就會被捕獲并且讓腳本繼續(xù)執(zhí)行。然而,隨著應(yīng)用程序規(guī)模的擴(kuò)大,這種方式將變得無法管理。
Angular
提供了一個默認(rèn)的ErrorHandler
,可以將錯誤消息打印到控制臺,因此可以攔截這個默認(rèn)行為來添加自定義的處理邏輯,下面嘗試編寫錯誤處理類:
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); } } }
通常在
app
下創(chuàng)建一個共享目錄shared
,并將此文件放在providers
文件夾中
現(xiàn)在,需要更改應(yīng)用程序的默認(rèn)行為,以使用我們自定義的類而不是ErrorHandler
。修改app.module.ts
文件,從@angular/core
導(dǎo)入ErrorHandler
,并將providers
添加到@NgModule
模塊,代碼如下:
import { NgModule, ErrorHandler } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { FormsModule } from "@angular/forms"; // Providers import { 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
提供了一種攔截HTTP請求/響應(yīng)的方法,就可以在傳遞它們之前處理。例如,可以在拋出錯誤之前重試幾次HTTP請求。這樣,就可以優(yōu)雅地處理超時,而不必拋出錯誤。
還可以在拋出錯誤之前檢查錯誤的狀態(tài),使用攔截器,可以檢查401狀態(tài)錯誤碼,將用戶重定向到登錄頁面。
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<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).pipe( retry(1), catchError((error: HttpErrorResponse) => { if (error.status === 401) { // 跳轉(zhuǎn)到登錄頁面 } else { return throwError(error); } }) ); } }
同樣需要添加到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"; // Providers import { 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 {}
多提供者用于創(chuàng)建可擴(kuò)展服務(wù),其中系統(tǒng)帶有一些默認(rèn)提供者,也可以注冊其他提供者。默認(rèn)提供程序和其他提供程序的組合將用于驅(qū)動系統(tǒng)的行為。
在控制臺打印錯誤日志對于開發(fā)者來說非常友好,但是對于用戶來說則需要一種更加友好的方式來告訴這些錯誤何時從GUI中發(fā)生。根據(jù)錯誤類型,推薦兩個組件:Snackbar
和Dialog
Snackbar
:推薦用于簡單的提示,比如表單缺少必填字段或通知用戶可預(yù)見的錯誤(無效電子郵件、用戶名太長等)。
Dialog
:當(dāng)存在未知的服務(wù)器端或客戶端錯誤時,推薦使用這種方式;通過這種方式,可以顯示更多的描述,甚至call-to-action
,比如允許用戶輸入他們的電子郵件來跟蹤錯誤。
在shared
文件夾中添加一個服務(wù)來處理所有通知,新建services
文件夾,創(chuàng)建文件:notification.service.ts
,代碼如下:
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"] }); } }
更新error-handler.ts
,添加NotificationService
:
import { ErrorHandler, Injectable, Injector } from "@angular/core"; import { HttpErrorResponse } from "@angular/common/http"; // Services import { NotificationService } from "../services/notification.service"; @Injectable() export class ErrorsHandler implements ErrorHandler { //Error handling需要先加載,使用Injector手動注入服務(wù) 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); } } }
如果在一個組件中拋出一個錯誤,可以看到一個很好的snackbar
消息:
當(dāng)然不能期望用戶向報(bào)告每個bug
,一旦部署到生產(chǎn)環(huán)境中,就不能看到任何控制臺日志。因此就需要能夠記錄錯誤的后端服務(wù)與自定義邏輯寫入數(shù)據(jù)庫或使用現(xiàn)有的解決方案,如Rollbar
、Sentry
、Bugsnag
。
接下來創(chuàng)建一個簡單的錯誤跟蹤服務(wù),創(chuàng)建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); } } }
將服務(wù)添加到error-handler.ts
中:
import { ErrorHandler, Injectable, Injector } from "@angular/core"; import { HttpErrorResponse } from "@angular/common/http"; // Services import { NotificationService } from "../services/notification.service"; import { LoggingService } from "../services/logging.service"; @Injectable() export class ErrorsHandler implements ErrorHandler { //Error handling需要先加載,使用Injector手動注入服務(wù) 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); } } }
到此,相信大家對“Angular中處理錯誤的方式是什么”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
當(dāng)前題目:Angular中處理錯誤的方式是什么
分享URL:http://bm7419.com/article26/jdejjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)、軟件開發(fā)、自適應(yīng)網(wǎng)站、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)