在尝试了更复杂的场景之后,没有解决方案,我回到了基础:
我有一个 web-api 控制器,当返回错误 500 时,我希望客户端能够捕获它。
出于某种原因 - 这没有发生 - 我可能在这里遗漏了一些东西。
当控制器处于正常状态时,该机制可以完美运行。
运行此代码时 - 在控制台中,我可以看到:错误 500 消息和错误和错误声明:“您提供了一个无效的对象,其中预期有一个流......”。
我在这里想念什么?
这是我的代码(手写,而不是复制+粘贴 - 忽略拼写错误):
控制器故意返回异常:
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;
}
}
角服务:
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')
);
}
}