Angular中处理错误的方式是什么

发布时间:2021-06-29 11:08:26 作者:chen
来源:亿速云 阅读:124

本篇内容主要讲解“Angular中处理错误的方式是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Angular中处理错误的方式是什么”吧!

什么是Angular

Angualr 是一款来自谷歌的开源的 web 前端框架,诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。

AngularJS 是基于声明式编程模式 是用户可以基于业务逻辑进行开发. 该框架基于HTML的内容填充并做了双向数据绑定从而完成了自动数据同步机制. 最后, AngularJS 强化的DOM操作增强了可测试性.

try/catch

最熟悉的的方式,就是在代码中添加try/catch块,在try中发生错误,就会被捕获并且让脚本继续执行。然而,随着应用程序规模的扩大,这种方式将变得无法管理。

ErrorHandler

Angular提供了一个默认的ErrorHandler,可以将错误消息打印到控制台,因此可以拦截这个默认行为来添加自定义的处理逻辑,下面尝试编写错误处理类:

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下创建一个共享目录shared,并将此文件放在providers文件夹中

现在,需要更改应用程序的默认行为,以使用我们自定义的类而不是ErrorHandler。修改app.module.ts文件,从@angular/core导入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

HttpInterceptor提供了一种拦截HTTP请求/响应的方法,就可以在传递它们之前处理。例如,可以在抛出错误之前重试几次HTTP请求。这样,就可以优雅地处理超时,而不必抛出错误。

还可以在抛出错误之前检查错误的状态,使用拦截器,可以检查401状态错误码,将用户重定向到登录页面。

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) {
          // 跳转到登录页面
        } 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 {}

多提供者用于创建可扩展服务,其中系统带有一些默认提供者,也可以注册其他提供者。默认提供程序和其他提供程序的组合将用于驱动系统的行为。

Notifications

在控制台打印错误日志对于开发者来说非常友好,但是对于用户来说则需要一种更加友好的方式来告诉这些错误何时从GUI中发生。根据错误类型,推荐两个组件:SnackbarDialog

shared文件夹中添加一个服务来处理所有通知,新建services文件夹,创建文件: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手动注入服务
  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消息:

日志和错误跟踪

当然不能期望用户向报告每个bug,一旦部署到生产环境中,就不能看到任何控制台日志。因此就需要能够记录错误的后端服务与自定义逻辑写入数据库或使用现有的解决方案,如RollbarSentryBugsnag

接下来创建一个简单的错误跟踪服务,创建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);
    }
  }
}

将服务添加到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手动注入服务
  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中处理错误的方式是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. go语言的错误处理方式是什么?
  2. JavaScript中错误正确处理方式,你对了吗?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular

上一篇:jquery如何模拟京东实现侧边栏导航效果

下一篇:php实现自动加载的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》