【发布时间】:2020-08-20 08:52:49
【问题描述】:
我有一个 .net Core web-api 应用程序。 我故意从控制器返回一个异常,但我没有看到在订阅的错误处理中处理该异常。 这是我的代码(手工复制,因此可能会出现拼写错误): 控制器:
public IActionResult getSomeErrorAsTest()
{
try
{
throw new Exception("Serer error");
}
catch(Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, new List<string>());
//throw ex;
}
}
角度服务:
export class MyService
{
MyDataSubject = new Subject<any[]>();
MyDataChanged :Observable>any[]> = this.MyDataSubject.asObservable();
subscribe :Subscription;
constructor(private httpClient : HttpClient)
{
this.subscribe = timer(0, 30000).pipe(
switchMap(()=>
this.getData())).subscribe();
}
getData()
{
return this.httpClient.get<any[]>(<controller url>)
.pipe(
tap(res =>
{
this.MyDataSubject.next(res);
}),
catchError(error =>
{
debugger;//I would expect to catch the debugger here, but nothing happens
return throwError(error);
})
)
}
}
组件:
export class MyComponent (private mySrv : MyService)
{
getMyData()
{
let sub =this.mySrv.MyDataChanged.subscribe(result => doSomething(),
error=> popUpAlert());
}
}
【问题讨论】:
-
你是说
catchError永远不会被执行吗?我可以看到为什么订阅中的错误回调永远不会执行,但catchError仍然应该执行一次。 -
@fridoo - 不,catchError 永远不会执行。我可以在我的控制台(开发人员工具)中看到错误 500 消息和“您在预期流的位置提供了一个无效对象......”错误消息。你怎么能看到订阅中的错误回调从来没有被执行过——是不是写的方式有问题?
-
在您的组件中订阅
this.mySrv.MyDataChanged。这个 observable 永远不会出错,因为您只将值推入其中 (this.MyDataSubject.next(res))。如果您在某个时候调用this.MyDataSubject.error(..),则会出错。但我不确定你是否想在这个流上抛出错误。如果一个可观察的错误它终止并且之后不能发出任何其他东西。似乎您希望 observable 永远不会终止,因为您使用无限计时器作为触发器。
标签: angular rxjs asp.net-core-webapi angular-errorhandler