为什么这个throwError没有被catchError捕获?
Why isn't this throwError being caught in catchError?
我正在尝试创建一个管道运算符并在不满足特定条件时抛出。但是我无法抛出并捕获错误。
这是我的管道:
// My custom pipeable
export function waitFor<T>(thisToComplete$: Observable<any>) {
return (beforeRunningThis$: Observable<T>) => {
return new Observable<T>(observer =>
thisToComplete$.pipe(first()).subscribe(x => {
if (x !== 'Success') {
console.log('Non success result encountered');
return throwError('Rando IO Error');
}
return beforeRunningThis$.subscribe(observer);
})
);
}
}
消费代码:
const preReq$ = timer(1000);
const dataReq$ = getData();
try {
dataReq$
.pipe(waitFor(preReq$), catchError(x => {
console.log('Code here reached');
return of('Error was handled either here')
}))
.subscribe(x => console.log(`I have result ${x.toString()}`));
} catch (e) {
console.log('Error was handled here');
}
None 但是上面的控制台日志。
这是一个stackblitz
由于您使用的是 Observable 结构
observer.error
就是你的投掷方式
if (x !== 'Success') {
console.log('Non success result encountered');
observer.error('Rando IO Error');
}
您需要删除管道运算符中的错误处理。基本上你在那里消费错误:
dataReq$
.pipe(waitFor(preReq$))
.subscribe(x => {
console.log(`I have result ${x.toString()}`);
}, error => {
console.log('Code here reached');
// handle error
});
我正在尝试创建一个管道运算符并在不满足特定条件时抛出。但是我无法抛出并捕获错误。
这是我的管道:
// My custom pipeable
export function waitFor<T>(thisToComplete$: Observable<any>) {
return (beforeRunningThis$: Observable<T>) => {
return new Observable<T>(observer =>
thisToComplete$.pipe(first()).subscribe(x => {
if (x !== 'Success') {
console.log('Non success result encountered');
return throwError('Rando IO Error');
}
return beforeRunningThis$.subscribe(observer);
})
);
}
}
消费代码:
const preReq$ = timer(1000);
const dataReq$ = getData();
try {
dataReq$
.pipe(waitFor(preReq$), catchError(x => {
console.log('Code here reached');
return of('Error was handled either here')
}))
.subscribe(x => console.log(`I have result ${x.toString()}`));
} catch (e) {
console.log('Error was handled here');
}
None 但是上面的控制台日志。
这是一个stackblitz
由于您使用的是 Observable 结构
observer.error
就是你的投掷方式
if (x !== 'Success') {
console.log('Non success result encountered');
observer.error('Rando IO Error');
}
您需要删除管道运算符中的错误处理。基本上你在那里消费错误:
dataReq$
.pipe(waitFor(preReq$))
.subscribe(x => {
console.log(`I have result ${x.toString()}`);
}, error => {
console.log('Code here reached');
// handle error
});