全局异常处理与统一异常处理_角度的全局错误处理

全局异常处理与统一异常处理

A not always so popular but for the end user enormously important topic is the interception of errors. Even if an application has been thoroughly tested before deployment, it is always possible that the user may encounter errors. In this article you will learn how to catch various errors in Angular — one of the world’s most popular front end frameworks — at a global location and process them accordingly.

对于终端用户来说,一个并非总是如此流行但极为重要的话题是拦截错误。 即使在部署之前已经对应用程序进行了彻底的测试,用户也很可能会遇到错误。 在本文中,您将学习如何在全球位置捕获Angular (世界上最流行的前端框架之一)中的各种错误,并进行相应的处理。

错误类型 (Error Types)

Since nowadays more and more logic is outsourced from the back end to the front end, the probability increases that a faulty behavior of the user leads to an unforeseen error, which can cause the application to “crash”. Now a web application cannot really “crash” like a desktop application, which in the worst case simply closes. No, the web application remains open in the current browser tab, only its behavior is no longer comprehensible to the user in case of an error. Since JavaScript is single-threaded in the browser, it can happen that a part of the interface freezes and an action is not performed correctly. In this case we speak of a local front end error. Since we as the developers don’t know where and when such an error could occur, it is important to catch all occurring errors at a central location.

由于如今越来越多的逻辑从后端外包给前端,因此用户的错误行为导致无法预料的错误的可能性增加,这可能导致应用程序“崩溃”。 现在,Web应用程序无法像桌面应用程序那样真正“崩溃”,在最坏的情况下,桌面应用程序会关闭。 不可以,Web应用程序在当前浏览器选项卡中保持打开状态,只有错误时用户才无法理解其行为。 由于JavaScript在浏览器中是单线程的,因此可能会发生一部分接口冻结,并且未正确执行操作的情况。 在这种情况下,我们说的是本地前端错误。 由于我们(作为开发人员)不知道在何时何处会发生此类错误,因此在中心位置捕获所有发生的错误非常重要。

Another error case that can occur is when a request to the back end fails and the front end receives an error message from the back end. Although in this case it is clear that the error is coming from the back end, there is a need to take care of the error handling for every single request to the back end. Again, it is better to handle these errors in a centralized location so that the user is presented with consistent error messages and also to avoid forgetting to intercept errors.

可能发生的另一种错误情况是,对后端的请求失败,并且前端收到来自后端错误消息。 尽管在这种情况下很明显错误是来自后端的,但仍需要照顾到对后端的每个请求的错误处理。 同样,最好在集中的位置处理这些错误,以便向用户显示一致的错误消息,并避免忘记拦截错误。

应用范例 (Example application)

In the following we will look at an example application that uses global error handling and go through it step by step. A click on the first two buttons produces an error — the first a local front end error, the second via a bad response from the back end. The third button shows a successful request, where no error message is displayed, but only the loading spinner until the request is completed.

在下面的内容中,我们将研究一个使用全局错误处理的示例应用程序,并逐步进行操作。 单击前两个按钮会产生错误-第一个是本地前端错误,第二个是来自后端的错误响应。 第三个按钮显示成功的请求,其中不显示错误消息,但仅显示加载微调器,直到请求完成为止。

应用架构(Application architecture)

Before we turn our attention to the implementation details, we should also take a look at the structure of our Angular application. In a more complex application it is worthwhile to divide certain functionalities into different modules. For example, as in our case, there is a core module that contains the functionality that is globally available to the whole application and is also loaded immediately when the application is started — such as the error handling.

在我们将注意力转移到实现细节之前,我们还应该看一下Angular应用程序的结构。 在更复杂的应用程序中,值得将某些功能划分为不同的模块。 例如,在我们的案例中,有一个核心模块,其中包含整个应用程序全局可用的功能,并且在应用程序启动时也会立即加载该功能-例如错误处理。

Another typical module is the shared module. As the name suggests, this module contains functionality that can be reused in several other modules of the application. These are mostly stateless user interface components (or so-called dump components), such as loading spinners or dialogs, which can be controlled by a service. In our case there are two dialogs, one for displaying the error message and one for displaying a loading spinner, which is displayed for the duration of a request.

另一个典型的模块是共享模块。 顾名思义,此模块包含可以在应用程序的其他几个模块中复用的功能。 这些大多是无状态的用户界面组件(或所谓的转储组件),例如可以由服务控制的加载微调器或对话框。 在我们的示例中,有两个对话框,一个用于显示错误消息,一个用于显示加载微调器,该对话框在请求期间显示。

档案结构 (File structure)

In the following a simplified structure of the files is shown. You can directly see the separation into core and shared modules. In this case, the shared directory contains the components and services needed to display the error messages and the loading spinner. The core directory in turn contains the files for the interceptors that globally intercept and process the errors in the application. Both the core module and the shared module are imported into the app module, which is usually the entry module of an application in Angular.

下面显示了文件的简化结构。 您可以直接看到核心模块和共享模块的分离。 在这种情况下,共享目录包含显示错误消息和加载微调器所需的组件和服务。 核心目录又包含拦截器的文件,这些文件可全局拦截并处理应用程序中的错误。 核心模块和共享模块都被导入到app模块中,后者通常是Angular中应用程序的输入模块。

📦 src
┣ 📂 core
┃ ┣ 📂 errors
┃ ┃ ┣ 📜 error-handler.module.ts
┃ ┃ ┣ 📜 global-error-handler.ts
┃ ┃ ┗ 📜 http-error.interceptor.ts
┃ ┗ 📜 core.module.ts
┣ 📂 shared
┃ ┣ 📂 errors
┃ ┃ ┣ 📂 error-dialog
┃ ┃ ┗ 📜 error-dialog.service.ts
┃ ┣ 📂 loading
┃ ┃ ┣ 📂 loading-dialog
┃ ┃ ┗ 📜 loading-dialog.service.ts
┃ ┗ 📜 shared.module.ts
┗ 📜 app.module.ts

错误处理模块 (Error Handler Module)

The Error Handler module is the entry point for the global Error Handler. It is part of the core module and registers two providers. The first one is responsible for the general error handling, which catches all errors occurring within our application. The second provider is an HTTP interceptor, which is called for every interaction with the back end. The multi property must always be set to true in this case, since the HTTP_INTERCEPTORS injection token can potentially be assigned to several classes.

错误处理程序模块是全局错误处理程序的入口点。 它是核心模块的一部分,并注册了两个提供程序。 第一个负责一般的错误处理,它捕获了我们应用程序中发生的所有错误。 第二个提供者是HTTP拦截器,与后端的每次交互均被调用。 在这种情况下,必须始终将multi属性设置为true ,因为可以将HTTP_INTERCEPTORS注入令牌分配给多个类。

@NgModule({
  declarations: [],
  imports: [CommonModule],
  
  // register the classes for the error interception here
  providers: [
    { 
      // processes all errors
      provide: ErrorHandler, 
      useClass: GlobalErrorHandler 
    },
    { 
      // interceptor for HTTP errors
      provide: HTTP_INTERCEPTORS, 
      useClass: HttpErrorInterceptor, 
      multi: true // multiple interceptors are possible
    }
  ]
})
export class ErrorHandlerModule {}

全局错误处理程序(Global Error Handler)

As you have seen in the last section, the GlobalErrorHandler class was registered as provider in the Error Handler module. This class implements the ErrorHandler class and contains a handleError method. This method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method. In our case a dialog is opened where the error message should be displayed and the error is logged to the browser console.

如上一节所述, GlobalErrorHandler类已在Error Handler模​​块中注册为提供程序。 此类实现ErrorHandler类,并包含一个handleError方法。 每当在应用程序中某处引发错误时,都会调用此方法。 该错误将作为参数传递,并且可以在方法内部进行进一步处理。 在我们的情况下,将打开一个对话框,其中应显示错误消息,并将错误记录到浏览器控制台。

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private errorDialogService: ErrorDialogService) {}


  handleError(error: Error) {
    this.errorDialogService.openDialog(
      error.message || "Undefined client error"
    );
    console.error("Error from global error handler", error);
  }
}

In our example there is a method in the AppComponent called localError which throws an error:

在我们的示例中, AppComponent有一个名为localError的方法,该方法会引发错误:

localError() {
throw Error("The app component has thrown an error!");
}

So, if the first button in the example is clicked it will call this method and the GlobalErrorHandler processes the thrown error by showing this dialog:

因此,如果单击示例中的第一个按钮,它将调用此方法,并且GlobalErrorHandler通过显示此对话框GlobalErrorHandler处理引发的错误:

Image for post

The user can then click on the “Close” button to close the error dialog and continue using the application. Of course, the processing of an error may vary from case to case and require further steps. For example, for monitoring purposes, it can be useful to write the error message to a log file in the back end, to navigate the application to another page or to reset a certain state. In this example we simply show the error dialog.

然后,用户可以单击“关闭”按钮以关闭错误对话框并继续使用该应用程序。 当然,错误的处理可能因情况而异,并且需要进一步的步骤。 例如,出于监视目的,将错误消息写入后端的日志文件,将应用程序导航到另一个页面或重置特定状态可能很有用。 在此示例中,我们仅显示错误对话框。

HTTP错误拦截器 (HTTP Error Interceptor)

The interception of HTTP errors is done by an HTTP Interceptor class. The HttpErrorInterceptor class implements the interface HttpInterceptor by providing the method intercept. This method is called automatically on every HTTP request that is made through our application — regardless of whether it was successful or not. This also allows us to set up a loading spinner. The first thing we do is to call the service for the Loading Spinner dialog to display it:

HTTP错误的拦截是由HTTP Interceptor类完成的。 所述HttpErrorInterceptor类实现的接口HttpInterceptor通过提供方法intercept 。 在通过我们的应用程序发出的每个HTTP请求上都会自动调用此方法-不管请求是否成功。 这也使我们可以设置加载微调器。 我们要做的第一件事是调用“加载微调器”对话框中的服务以显示它:

this.loadingDialogService.openDialog();

The dialog for the loading spinner will be opened and lets the user know that an interaction with the back end is currently taking some time:

将打开用于加载微调器的对话框,并让用户知道当前与后端的交互需要一些时间:

Image for post

After this the processing of the HTTP request is executed which is basically done with an HTTP handler called next. The HTTP handler provides ahandle method that processes all HTTP requests by returning an RxJS observable. Based on this observable the pipe method can be called which provides us the possibility to use some RxJS operators to handle the requests one after each other.

此后,将执行HTTP请求的处理,这基本上是通过一个称为next的HTTP处理程序完成的。 HTTP处理程序提供了一个handle方法,该方法通过返回可观察到的RxJS来处理所有HTTP请求。 基于此可观察到的方法,可以调用pipe方法,这为我们提供了使用某些RxJS运算符依次处理请求的可能性。

Here we’re using the operator catchError that is executed when an error is thrown because of a bad request to the back end. As a first action the error is simply logged to the console in the web browser. At next, the service for the error dialog is called to open the dialog with the error message and the status code of the error response (e.g. 404). Finally, we have to return the emitted error notification by calling throwError with the error as argument.

这里我们使用的操作符catchError是由于对后端的错误请求而引发错误时执行的。 第一步,将错误记录到Web浏览器的控制台中。 接下来,调用错误对话框的服务以打开包含错误消息和错误响应的状态代码的对话框(例如404)。 最后,我们必须通过以错误为参数调用throwError来返回发出的错误通知。

With the help of the finalize operator the dialog of the loading spinner is hidden again, regardless of whether the request has thrown an error — i.e. catchError was called — or not.

借助于finalize运算符,无论请求是否引发错误(即catchError调用catchError ),加载微调器的对话框都再次被隐藏。

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(
    private errorDialogService: ErrorDialogService,
    private loadingDialogService: LoadingDialogService
  ) {}


  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // show loading spinner
    this.loadingDialogService.openDialog();
    
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error("Error from error interceptor", error);
        
        // show dialog for error message
        this.errorDialogService.openDialog(error.message ?? JSON.stringify(error), error.status);
        return throwError(error);
      }),
      finalize(() => {
        // hide loading spinner
        this.loadingDialogService.hideDialog();
      })
    ) as Observable<HttpEvent<any>>;
  }
}

In our sample application you can see that the following HTTP request does not need any additional error handling:

在我们的示例应用程序中,您可以看到以下HTTP请求不需要任何其他错误处理:

failingRequest() {
this.http.get("https://httpstat.us/404?sleep=2000").toPromise();
}

The error dialog will look like this:

错误对话框如下所示:

Image for post

Finally, it should be noted that the global error handler also became aware of the HTTP error (you can see this in the browser console). In this case, however, no separate dialog window for the error was opened, because the service for the error dialog was already triggered by the HTTP error interceptor before and in this case prevented a second dialog from being opened at the same time. In general you can find some examples on the net, which use the instanceOf operator within the global error handler to distinguish if it is an HTTP error or not. In this case, the entire error handling — including the HTTP errors — would be handled by the global error handler. With the current Angular version (v. 10) this is not possible because both error types are simply recognized as “Error” by instanceOf and there is no further information about whether it is an HTTP error or not. Therefore this article shows an alternative approach to achieve the same error handling but with having it separated into the error handler, which catches everything and an interceptor, which only takes care of the HTTP errors.

最后,应该注意的是,全局错误处理程序也意识到了HTTP错误(您可以在浏览器控制台中看到此错误)。 但是,在这种情况下,没有打开单独的错误对话框窗口,因为错误对话框的服务之前已经由HTTP错误拦截器触发,在这种情况下,阻止了同时打开第二个对话框。 通常,您可以在网上找到一些示例,这些示例在全局错误处理程序中使用instanceOf运算符来区分它是否是HTTP错误。 在这种情况下,整个错误处理(包括HTTP错误)将由全局错误处理程序处理。 在当前的Angular版本(v。10)中,这是不可能的,因为两种错误类型都被instanceOf简单地识别为“错误”,并且没有关于是否为HTTP错误的进一步信息。 因此,本文展示了另一种方法来实现相同的错误处理,但将其分隔为错误处理程序,该错误处理程序可以捕获所有内容,而拦截器则仅处理HTTP错误。

结论 (Conclusion)

The approach of this article shows that setting up an overall error handler is of great advantage. Although there is some initial setup effort, in the long run you get a consistent error handling that you don’t have to worry about when adding new features to the application in the future. The same applies to the loading spinner which is automatically displayed for each request. Of course only the basics were shown here, individual adaptations and extensions to this approach are possible, depending on the requirements of the respective application.

本文的方法表明,设置总体错误处理程序具有很大的优势。 尽管需要一些初始设置工作,但从长远来看,您将获得一致的错误处理,以后在向应用程序中添加新功能时不必担心。 这同样适用于针对每个请求自动显示的加载微调器。 当然,这里仅显示了基础知识,根据相应应用程序的要求,可以对该方法进行单独的修改和扩展。

源代码 (Source Code)

翻译自: https://medium.com/@PhilippKief/global-error-handling-in-angular-ea395ce174b1

全局异常处理与统一异常处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值