【问题标题】:catchError Not working when returning error 500 from web-api从 web-api 返回错误 500 时 catchError 不工作
【发布时间】:2020-12-12 08:59:54
【问题描述】:

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

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

【问题讨论】:

  • handleError重新抛出错误的目的是什么?

标签: angular exception asp.net-web-api rxjs angular-errorhandler


【解决方案1】:

这是因为你需要使用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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多