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

标签 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),我需要指定处理订阅中错误回调中错误的方式,但是我无法做到这一点,因为解析器是管理订阅的人。

有没有一种方法可以指定解析器应如何处理错误?

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

最佳答案

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

这将检查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});
    }
  }

关于error-handling - Angular GlobalErrorHandler和HttpErrorResponse-解析器抛出格式错误的HttpErrorResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51631492/

相关文章:

ruby-on-rails - Rails 4 : ActionView::MissingTemplate even though view is defined?

angular6 - Angular 6 中带有选择框的 ngForm 简单示例

Angular 2+ - 数据加载 : best practices

java - @ControllerAdvice 类中的信息传递到哪里

php - codeigniter 错误日志文件仅显示通知错误但错误消息未显示在屏幕上

.net - 我可以同时为前端和后端设置 ngrok 吗?

javascript - 如何使用 Angular 6从纬度和经度获取地址

angular - 如果添加另一个数据流,解析器不会解析

javascript - Angular 8 解析器未解析

php - PHP中的错误处理并重定向到错误页面