【发布时间】:2019-08-13 11:43:19
【问题描述】:
当我从路由中定义的变量selectionId 为空值或无效值时,我试图弄清楚如何捕获错误。目前,如果我的 category 变量未定义,它会被 rxjs 函数 catchError 捕获,并适当地抛出我的错误订阅块。
但是当selectionId未定义时,它仍然进入成功块,成功的结果未定义。
loadSelection() {
// define the menu category chosen (e.g. 'pizza')
const category = this.route.snapshot.url[0].path;
// define which item in the menu was selected (e.g. 1)
const selectionId = this.route.snapshot.url[1].path;
// in the menu state at the given category, find the menu item with the matching selectionId
this.store.select('menu')
.pipe(map(menuState => menuState.menu.groupedMenu[category]
.find(selection => selection._id === selectionId)),
catchError(err => throwError('given category does not exist'))
).subscribe(
(selection: Selection) => { // success case
this.selection = selection;
},
(err) => { // error case
console.log('weow', err);
});
}
当我的.find 返回未定义时,处理错误的最佳方法是什么?
我可以在我的成功块中放置一个 if 语句来检查 undefined,但我不觉得这是干净的代码。但也许我错了。
感谢您的帮助
【问题讨论】:
-
这是一种偏好/意见,但我的立场是,错误意味着出现了您不打算或未预料到的错误。如果您的流可以返回 undefined 并且您知道它,那么您只是在处理流的状态。很多人不会同意并认为错误可能是预期的或预期的,将其作为错误处理更干净。不过这真的取决于你。
-
是否需要默认的 selectionId ?
-
没有@FanCheung,不需要
-
@bryan60 你说得很好。对我来说,这里有两个错误处理案例很奇怪
标签: javascript angular rxjs ngrx