Angular 从web api返回错误500时catchError不工作
在尝试了更复杂的场景后,如果没有解决方案,我将返回到基础: 我有一个web api控制器,当返回错误500时,我希望客户端能够捕获它 出于某种原因——这并没有发生——我可能遗漏了一些东西 当控制器处于正常状态时,该机构工作正常 运行此代码时-在控制台中,我可以看到:错误500消息和一个错误和错误声明:“您提供了一个无效的对象,其中需要流…” 我错过了什么 这是我的代码(手写,不是复制+粘贴-忽略打字错误): 控制器故意返回异常:Angular 从web api返回错误500时catchError不工作,angular,exception,asp.net-web-api,rxjs,angular-errorhandler,Angular,Exception,Asp.net Web Api,Rxjs,Angular Errorhandler,在尝试了更复杂的场景后,如果没有解决方案,我将返回到基础: 我有一个web api控制器,当返回错误500时,我希望客户端能够捕获它 出于某种原因——这并没有发生——我可能遗漏了一些东西 当控制器处于正常状态时,该机构工作正常 运行此代码时-在控制台中,我可以看到:错误500消息和一个错误和错误声明:“您提供了一个无效的对象,其中需要流…” 我错过了什么 这是我的代码(手写,不是复制+粘贴-忽略打字错误): 控制器故意返回异常: public IActionResult getSomeError
public IActionResult getSomeErrorAsTest()
{
try
{
/*usually it does something on the server*/
throw new Exception("Serer error");
}
catch(Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, new List<string>());
//throw ex;
}
}
这是因为您需要使用rxjs库中的“throwError”,它实际上返回一个抛出错误的可观察对象 一个有效的例子:
投掷者博士:经过大量测试,发现问题出在HTTP_拦截器上,它可能会“捕获”错误响应。在
handleError
中重新抛出错误的目的是什么?
export class MyService
{
getData()
{
return this.httpClient.get<void>(<controller url>)
/*not sure if this part is needed*/
.pipe
(
catchError(this.handleError);
)
}
handleError(error : HttpErrorResponse)
{
return Observable.throw(error.message || "server error");
}
}
export class myComponent
{
isGettingData : boolean;
constructor (private mySrv : MyService)
ngOnInit()
{
this.isGettingData = false;
}
public getData()
{
this.isGettingData = true; //This is used for indication icon in the Html, in case the server action takes few seconds
this.mySrv.getDataFromBackEndServer().subscribe
(
result => this.isGettingData = false,
error => {
console.log('eror occured');
this.isGettingData = false;
},
() => console.log('completed')
);
}
}