我写了一个函数pipe
-有能力的:
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
链接错误吗?关键词?我试图返回
Observable.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
不再修改原型(prototype)以包含运算符或这些“创建运算符”,而是将它们作为独立函数公开。您可以阅读更多信息 here ,但它的要点是您只需 return throwError(…)
,例如return source$.pipe(
catchError(err => err.code === 404
? throwError("Not found")
: throwError(err)
)
)
关于rxjs - 如何通过 catchError() 正确传播错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295564/