Angular GlobalErrorHandler和HttpErrorResponse-解析器抛出格式错误的HttpErrorResponse

时间:2018-08-01 10:53:52

标签: error-handling angular6 angular-resolver angular-errorhandler

我已经在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),我需要指定处理订阅中错误回调中错误的方法,但我不能这样做,因为解析器是管理订阅的人。

是否可以指定解析器应如何处理错误?

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

1 个答案:

答案 0 :(得分: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});
    }
  }