4

在尝试了更复杂的场景之后,没有解决方案,我回到了基础:

我有一个 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')
        );
    }
}
4

2 回答 2

1

经过大量测试,头发拉扯 - 它发现问题出在 HTTP_INTERCEPTORS 可能“钓鱼”错误响应。

于 2020-08-24T06:34:40.087 回答
0

这是因为您需要使用 rxjs lib 中的“throwError”,它实际上返回了一个抛出错误的 observable

一个工作示例:https ://stackblitz.com/edit/rxjs-catcherror-http?file=src/app/test-service.service.ts

throwError 文档:https ://rxjs-dev.firebaseapp.com/api/index/function/throwError

于 2020-08-23T16:36:52.243 回答