2

我在 Angular 6 应用程序中创建了全局错误处理程序:

主要错误处理方法:

handleError(error: Error | HttpErrorResponse) {
    const router = this.injector.get(Router);
    const notificationService = this.injector.get(NotificationsService);

    this._logger(error);

    if (!navigator.onLine) {
        notificationService.displayNotification('error', 'timespan', {heading: 'Internet connection lost!', body: ''});
    } else if (error instanceof HttpErrorResponse) {
        notificationService.displayNotification('error', 'click', this._httpErrorMessage(error));
    } else {
        // CLIENT error
        router.navigate(['/error-page']);
    }
}

问题:许多 HTTP 服务调用是在解析器中执行的:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ClientDetailsModel> {
if (route.params.cif) {
  const reqBody = new GetClientDetailsRequestModel({cif: route.params.cif, idWewPrac: this.userContext.getUserSKP()});
  return this.clientsService.getClientDetails(reqBody)
    .pipe(
        map((clientDetails: { customerDetails: ClientDetailsModel }) => {
            if (clientDetails.customerDetails) {
                return clientDetails.customerDetails;
            }
            return null;
        })
    );
}

如果在这样的调用中发生 Http 错误,我的全局错误处理程序收到的错误将形成为包裹在 Error 中的 HttpErrorResponse(错误消息是 HttpErrorResponse):

Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":400,"statusText":"OK","url":"https://...

如果 Http 错误发生在解析器之外,则全局错误处理程序可以正常工作。

为了达到我的目标(从解析器抛出 HttpErrorResponse),我需要指定在订阅内的错误回调中处理错误的方式,但我不能这样做,因为解析器是管理订阅的人。

有没有办法指定解析器应该如何处理错误?

我想避免手动解析这些包装错误。

4

1 回答 1

0

我正在寻找解决方案,但只能创建一个工作循环。

这将检查 HttpErrorResponse 文本并尝试将 JSON 解析为真正的错误对象。

一点都不好,但总比没有好。

  handleError(error: any): void {
    console.error('Errorhandler catched error: ' + error.message, error);
    // We need to have this little hack in oder to access the real error object
    // The Angular resolver / promise wraps the error into the message, serialized as json.
    // So we extract this error again.
    // But first lets check if we actually dealing with an HttpErrorResponse ...
    if (error.message.search('HttpErrorResponse: ')) {
      // The error includes an HTTPErrorResponse, so we try to parse it's values ...
      const regex = new RegExp('^.*HttpErrorResponse:\\s(\\{.*\\})$');
      const matches = regex.exec(error.message);
      if (matches !== null) {
        // matches the regex, convert...
        const httpErrorResponse = JSON.parse(matches[1]); // This is now the real error object with all the fields
        this.handleHttpErrorResponse(httpErrorResponse);
      } else {
        // It contains HttpErrorResponse, but no JSON part...
        this.toastr.error('There was an unknown communication error',
          'Communication error',
          {timeOut: 10000});
      }
    } else {
      this.toastr.error('Unknown error occured',
        'Well that should not happen. Check the log for more information...',
        {timeOut: 10000});
    }
  }
于 2019-05-07T20:41:23.720 回答