如何处理解析器中的错误

2024-04-29

我正在尝试使用解析器来打造更好的用户体验。在幸福的道路上,一切都进展顺利。我似乎无法弄清楚如何处理异常。我的解析器调用一个服务,该服务会访问一个 webapi 项目。一个例子:

Foo解析器:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Foo> {
      return this.fooService.getById(route.params['id']).catch(err => {
    ****not sure what to do/return in the case of a server error****
    return Observable.throw(err);
  });
} 

食品服务:

  public getById(id: string): Observable<Foo> {
    return this.http.get(`${ this.apiUrl }/${ id }`)
        .map(this.extractData)
        .catch(this.handleError);
}

处理错误函数:

   protected handleError (error: Response | any) {
    // Todo: Log the error   
    // Errors will be handled uniquely by the component that triggered them
    return Observable.throw(error);
}

在 FooComponent 内部,我执行此操作(如果从服务/解析器返回错误,则永远不会触发此操作):

Foo组件:

ngOnInit(): void {
    this.foo= this.route.snapshot.data['foo'];
    if (this.foo) {
       this.createForm(this.foo);
    }
}

我尝试抛出错误(如图所示) - 我在控制台中收到此异常:

未捕获(承诺):响应状态:500 内部服务器错误 对于网址:

并返回new Observable<Foo>(), 这使:

无法读取未定义的属性“订阅”

我有一些解析器,所有这些解析器都可能在服务器上遇到异常,但我不知道在发生这些异常时该怎么办。


这是我的一个解析器的错误处理示例,使用了 Gunter 建议的技术:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Injectable()
export class ProductResolver implements Resolve<IProduct> {

    constructor(private productService: ProductService,
                private router: Router) { }

    resolve(route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<IProduct> {
        let id = route.params['id'];
        if (isNaN(+id)) {
            console.log(`Product id was not a number: ${id}`);
            this.router.navigate(['/products']);
            return Observable.of(null);
        }
        return this.productService.getProduct(+id)
            .map(product => {
                if (product) {
                    return product;
                }
                console.log(`Product was not found: ${id}`);
                this.router.navigate(['/products']);
                return null;
            })
            .catch(error => {
                console.log(`Retrieval error: ${error}`);
                this.router.navigate(['/products']);
                return Observable.of(null);
            });
    }
}

您可以在这里找到完整的示例:https://github.com/DeborahK/Angular-Routing https://github.com/DeborahK/Angular-Routing在 APM-final 文件夹中。

2019 年 2 月更新

这是解析器中错误处理的更好答案:

  1. 使用可选的错误属性将您的接口包装在另一个接口中:
/* Defines the product entity */
export interface Product {
  id: number;
  productName: string;
  productCode: string;
  category: string;
  tags?: string[];
  releaseDate: string;
  price: number;
  description: string;
  starRating: number;
  imageUrl: string;
}

export interface ProductResolved {
  product: Product;
  error?: any;
}
  1. 解析到该接口:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { ProductResolved } from './product';
import { ProductService } from './product.service';

@Injectable({
  providedIn: 'root',
})
export class ProductResolver implements Resolve<ProductResolved> {
  constructor(private productService: ProductService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ProductResolved> {
    const id = route.paramMap.get('id');
    if (isNaN(+id)) {
      const message = `Product id was not a number: ${id}`;
      console.error(message);
      return of({ product: null, error: message });
    }

    return this.productService.getProduct(+id).pipe(
      map((product) => ({ product: product })),
      catchError((error) => {
        const message = `Retrieval error: ${error}`;
        console.error(message);
        return of({ product: null, error: message });
      }),
    );
  }
}
  1. 在组件中,拉出您需要的接口部分:
ngOnInit(): void {
  const resolvedData: ProductResolved = this.route.snapshot.data['resolvedData'];
  this.errorMessage = resolvedData.error;
  this.product = resolvedData.product;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何处理解析器中的错误 的相关文章

  • mat-table 中每行的 formGroup 数组

    我有一个 formGroup 数组 其中每个元素代表一个表单 接下来我有一个 mat 表 我想要做的是将每个 tr 即每一行 生成为不同的表单 以便表的第 i 行链接到第 i 个 formGroup 因此 在第 i 行内 每个 td 元素都
  • Angular2 authguards 执行异步函数失败

    我想通过检查用户是否从服务器登录来保护我的路由 但异步函数不会被执行 这是我的代码 canActivate route ActivatedRouteSnapshot state RouterStateSnapshot Observable
  • 数字和文本列的垫排序问题

    我有角度材料数据源 角度材料版本是 5 0 3 排序正在进行中 但是对于某些列 它的排序不正确 那里有数字和文字 例如 排序结果如 XXX 1 1tesxt 1 OPD OXD 12
  • Angular 5 中使用 rxjs 进行持久订阅

    我对 Angular 5 中的 rxjs 仍然有点陌生 并且很难表达我的问题 我仍然希望得到一些提示 我经常会得到相同的设置 多个组件显示相同的数据 访问数据的单个服务 现在通过 Observables 接收数据时我有 2 个选择 a 订阅
  • mat-tab-group 不是 Angular 9 中的已知元素

    我正在使用 Angular 9 和 Angular Material 9 2 4 我正在尝试使用mat tab 组在我的 component html 中 但我不断收到错误 mat tab group is not a known elem
  • 令牌中不存在必需的声明 nbf(使用 Firebase Microsoft Sign In 尝试访问 Microsoft Graph)

    我目前有一个具有以下结构的应用程序 Angular 前端 Node js 服务器 我们已实施 Google Cloud 的身份提供商以使用 Google 和 或 Microsoft 进行登录 Google 登录并访问 Google Clou
  • 如何禁用 Ionic2 / Angular2 上的“未使用的导入”警告

    我知道有一个选项可以禁用这些 未使用的导入 警告tslint跑步时ionic serve or ionic build 但我不知道该把它放在哪里 有人知道吗 谢谢 1 https palantir github io tslint rule
  • http.put 请求在 Angular2 中执行两次

    我正在尝试更新从我的 Angular2 应用程序调用 API 的公司记录 我在调试时注意到 http 调用被执行了两次 我找到了另一个堆栈溢出线程 https stackoverflow com questions 37241294 ang
  • 不同事件的角度停止传播

    在我的 Angular 4 应用程序中 我有一个带有 dblclick 处理程序的父组件和一个带有 click 处理程序的子组件 组件 html
  • Angular4 - 滚动到锚点

    我正在尝试对同一页面上的锚元素进行简单的滚动 基本上 用户点击 尝试 按钮 它就会滚动到页面下方 ID 为 登录 的区域 现在 它正在与一个基本的id login a href login a 但它正在跳转到该部分 理想情况下 我希望它滚动
  • ngrx 存储是否持久?

    ngrx 存储是否持久 换句话说 我们可以关闭浏览器重新打开它 并检索添加到ngrx 商店 https github com ngrx platform 目前 ngrx store 不支持此类功能 但是您可以通过使用类似的库来维护状态ngr
  • 如何测试包含自定义表单控件的组件?

    我有一个这样的组件 Component selector app custom form control templateUrl
  • MatAutocomplete 值 X 显示

    我的自动完成显示具有以下定义的对象的值 export class Person id number name string cityName string 这是自动完成模板
  • 在 Angular 中深度复制对象

    AngularJS 有angular copy 深度复制对象和数组 Angular 也有类似的东西吗 您还可以使用 JSON parse JSON stringify Object 如果它在你的范围内 那么它就存在于每个 Angular 组
  • 为什么 Angular 2 项目如此大 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们正在用 ng2 重写 ng1 项目 我们的 ng1 项目构建后大约有 8mb 我们对 ng2 的重写已经完成了大约四分之一 并且我
  • 415 不支持的媒体类型; Angular2 到 API

    我是 Angular 2 的新手 我面临着一个无法找到解决方案的问题 当我尝试从 Angular 2 发布到 API 时 我得到 415 不支持的媒体类型 角度2代码 onSubmit value any console log value
  • Angular 停止 Enter 键提交

    I am trying to stop the Enter from submitting my button and rather make it point to another function I tried trapping th
  • Angular 5 - 在加载数据之前停止未定义对象的错误

    防止控制台中因仍未定义的对象而出现错误的最佳方法是什么 假设我有这个 name string constructor private data DataService this data name subscribe res gt this
  • Angular Material 7 多重选择 - 设置选定值

    我正在尝试设置多选下拉列表的选定值 如下所示 循环根据条件选择多个复选框并进行设置 document getElementsByTagName mat pseudo checkbox index classList add mat pseu
  • 如何转义角度 HttpParams?

    在 Angular 服务中 我使用 HttpParams 将字符串发送到服务 get phone string Observable

随机推荐

  • PHP APC 潜在的缓存猛击避免了密钥

    我在尝试使用时收到此错误apc store 我用谷歌搜索了一下 发现这是APC定时炸弹错误并看到了一些建议添加的修复apc slam defense Off 到 php ini 我需要知道这是否是由于编程错误而发生的 如果是 如何修复它 这
  • 动态或在构建时连接和缩小 JavaScript - ASP.NET MVC

    作为这个问题的扩展这里在用户控件中链接 JavaScript 库 https stackoverflow com questions 885990 linking javascript libraries in user controls
  • 请求响应后正文中出现奇怪的字符

    我正在使用 NodeJS 和 Request 来发布 JSON 并获取其中包含数据的结果 我使用 Postman 设置此请求 并获取完全可读的 JSON 数据 d type Qvision WoningenModule Lib aanbod
  • 使用 Boost.spirit 解析简单的重复文本宏

    我正在学习如何使用 Boost Spirit 库来解析字符串 这似乎是一个非常好的工具 但也很困难 所以 我想解析一个字符串 其中一些单词用 并将它们放入字符串向量中 这是一个例子 word1 word2 word3 这是一个简单的任务 我
  • 具有活动样式的 React router 无法按照我对根 URL 的要求工作

    我在主菜单中使用了这个 NavLinks 问题是当 测试 汽车 链接被点击 Test 链接也正在应用样式 我相信这是因为 Test 假设是其他链接的根 所以这是有道理的 但我想要 Test 应用活动样式时 链接也可以像其他链接一样工作 所以
  • Zip 文件是使用 Windows 路径分隔符创建的

    我使用下面的代码创建一个 zip 文件 Zip 已正确创建 然后在我的程序中 我尝试从此文件中获取 zip 条目 如果我打印一个 zip 条目名称 我会得到 Windows 路径分隔符 例如 a b c 但我需要这样a b c 我还没有发布
  • 为什么连接没有在我的 iSeries/ASP.NET MVC 4 应用程序中重用?

    我们正在 Windows 2008 服务器场上运行 MVC 4 Web 应用程序 我们一直在尝试将服务器场升级到 Windows 2008 R2 64 位服务器 但在 iSeries 运行 V7R1 上遇到了连接池问题 我们经常调用 DB2
  • C#中如何判断一个数是正数还是负数?

    C 中如何判断一个数是正数还是负数 bool positive number gt 0 bool negative number lt 0
  • Python while 循环查找素数

    作为 Python 的第一个练习 我尝试编写一个使用循环来查找素数的程序 一切都适用于 for 循环 所以我尝试使用 while 循环 这可行 但程序返回一些不正确的数字 import math looking for all primes
  • “致命错误:调用未定义的函数 socket_create()”,即使在 php.ini 中启用

    我有一个奇怪的 PHP 问题 我在 Windows 7 的 IIS 上运行 PHP 5 当我在 PHP 文件中调用 socket create 时 如下所示 sock socket create AF INET SOCK DGRAM get
  • 如何为任何 exe 创建安装程序?

    我有 NET exe 我想为此创建一个设置 并且在任何登录或重新启动后应自动调用此 exe 当您部署 NET 应用程序时 可以采用多种方法来应对这一挑战 选择安装程序策略时 您必须考虑许多问题 这些包括 我计划如何分发该软件 该软件是否应该
  • 全局变量和静态变量存储在内存段的哪里?

    在我的链接器脚本中 起始地址和大小如下 code start 90400000 code end 90a00000 data start 90b00000 size 3MB bss start 91200000 size 1MB 但是当我声
  • 如何在 Amazon Linux 上安装最新版本的 GDAL?

    我想安装GDAL https gdal org 在运行 Amazon Linux 的 EC2 实例上 我认为它基于 RHEL 6 如果可能的话 我想避免从源代码编译 EPEL Yum 存储库中包含的 GDAL 版本对于我的目的来说太旧了 g
  • Akka 和 ReactiveMongo

    我正在尝试找到在集群工作人员之间共享相同连接池的最佳方法 我有以下结构 Master Actor gt Worker Actors 最多 100 个或更多 gt MongoDB 我想在工作人员和 MongoDB 之间放置reactivemo
  • 如何在 VC++ 中使用 _W64 和 __w64?

    有这样的事情 w64 http msdn microsoft com en us library s04b5w00 VS 71 aspx在 Visual C 9 中 我在尝试将本机 C DLL 移植到 64 位时遇到了它 特别是在crtde
  • JavaFX 中按下按钮的样式

    我有一个Button in my FXML文件 我在下面给它一个样式CSS button fx background color linear gradient ff5400 be1d00 fx background radius 30 f
  • 如何在 WPF 中绑定用户控件作为 DataGridTemplateColumn 失败

    我想使用来自不同程序集的用户控件作为 DataGridTemplateColumn 我已经看过很多例子和问题 比如this https stackoverflow com questions 13956767 binding to cust
  • 将 Microsoft.Office.Interop.Excel.Application 转换为 byte[]

    我正在代码中创建一个excel文件 如下所示 Microsoft Office Interop Excel Application excelFile CreateExcelFile 现在我想将此 excel 文件转换为 byte 而不保存
  • 旋转 ImageView 及其背景而不裁剪

    我已经进行了很多搜索 但找不到解决我的问题的方法 我不能使用android rotation因为我希望这个应用程序与 Android API 11 版本兼容 我的问题与此类似 在 Android 中旋转视图 https stackoverf
  • 如何处理解析器中的错误

    我正在尝试使用解析器来打造更好的用户体验 在幸福的道路上 一切都进展顺利 我似乎无法弄清楚如何处理异常 我的解析器调用一个服务 该服务会访问一个 webapi 项目 一个例子 Foo解析器 resolve route ActivatedRo