如何正确地通过 catchError() 传播错误?

How to propagate errors through catchError() properly?

我写了一个函数 pipe-able:

HandleHttpBasicError<T>()
{
    return ((source:Observable<T>) => {
        return source.pipe(
            catchError((err:any) => {
                let msg = '';
                if(err && err instanceof HttpErrorResponse)
                {
                    if(err.status == 0)
                        msg += "The server didn't respond";
                }
                throw {
                    err,
                    msg
                } as CustomError
            })
        )
        
    })
}

我可以在 HttpService:

中这样使用这个函数
checkExist(id:string)
{
    return this.http.head<void>(environment.apiUrl + 'some_url/' + id)
        .pipe(
            HandleHttpBasicError(),
            catchError((err:CustomError) => {
                if(err.msg)
                    throw err.msg;
                if(err.err.status == HttpStatusCodes.NOT_FOUND)
                    throw("It doesn't exist.");
                throw(err);
            })
            
        )
}

效果很好。当我订阅 checkExist() 时,我得到一个很好的错误消息,因为 HandleHttpBasicError 首先捕获错误并将其抛给服务的 catchError(),后者抛出错误消息,因为它不是 null.

这样,它允许我拥有一个全局 catchError() 来处理始终相同的错误消息。以后我会在HttpHandler,不过这不是重点

可以用 throw 关键字链接错误吗?

我试过returnObservable.throwError(),但是浏览器说

Observable.throwError is not a function

我的导入是 import {Observable, of, throwError} from 'rxjs';

这样做不是更好吗:

return ((source:Observable<T>) => {
        return source.pipe(
            catchError((err:any) => {
                msg = '';
                ...
                return of({err, msg} as CustomError)
                /* instead of
                throw(err)
                -or-
                return Observable.throwError(err) (which doesn't work)
                */
            })
        )
        
    })

?

Is it ok to chain the errors with the throw keyword ?

是的,完全没问题。 rxjs try-catch 此类情况并将其转换为错误通知。

I tryed to return Observable.throwError() but the browser say "Observable.throwError is not a function"

在 rxjs6 中,Observable 原型不再被修改为包含操作符或这些 »creation operators«,而是将它们作为独立函数公开。您可以阅读更多相关内容 here,但其要点是您只需 return throwError(…),例如

return source$.pipe(
  catchError(err => err.code === 404 
    ? throwError("Not found")
    : throwError(err)
  )
)