【问题标题】:Generic error handling between asp.net webapi and Angular 4asp.net webapi 和 Angular 4 之间的通用错误处理
【发布时间】:2026-01-01 05:20:05
【问题描述】:

我正在尝试将错误从我的 API 传递到 Angular 4 应用程序。问题是在角度方面我看不到正确的错误消息:

Web Api 错误是这样生成的:

        throw new HttpResponseException(
            new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Headers = {{"errorMessage", "Message in header"}},
                Content = new StringContent("Message in body")
            }
        );

我的角度代码类似于:

    return this._http.get<IMyObj[]>(this._serviceUrl)
      .do(this.handleSuccessResponse)
      .catch(this.handleErrorResponse);

    protected handleErrorResponse(err: HttpErrorResponse) {
        console.info(err);
        // some logic based on code
    }

问题是,如果我检查错误,它的“错误”属性为空,消息是“url 响应失败”并且没有自定义标头,但是在浏览器的网络选项卡上,我也可以看到我的自定义标头有错误作为身体的错误。如何从我的 Angular 应用程序访问这些消息?

【问题讨论】:

    标签: angular asp.net-web-api


    【解决方案1】:

    我的错误处理程序如下所示:

    private handleError(err: HttpErrorResponse) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = '';
        if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
    

    注意它使用statusmessage 属性,而不是error 属性。

    【讨论】:

    • 在我的客户端逻辑中,我实际上正在切换状态,并且对于每个状态代码,我都在做不同的事情。问题是 err.message 是“localhost:56219/api/v1/test 的 Http 失败响应:400 错误请求”,但在响应正文的网络选项卡中,我可以看到“正文中的消息”以及我的自定义标头。我的问题是如何在我的错误处理程序中访问响应正文(或自定义标头)。
    • 你有没有看到这个:github.com/angular/angular/pull/18466 它说它已经修复了。
    • 可能是一个非常基本的问题,但是我如何仅将角度更新到具有此修复程序的版本?我尝试了批量更新,但之后出现了问题:angular/core common 和 zone.js 正在成为未满足的依赖项。
    • 更新角度错误属性后现在有正文
    • @DeborahK 在这个例子中我们如何识别。什么是客户端错误,什么是服务器端错误?如果错误是实例错误,它是客户端?您能否添加更多关于如何在实际应用中使用它的代码,我的意思是您如何调用此 handleError 方法.. 谢谢 Deborah!
    【解决方案2】:

    你可以试试这个。

    在此我传递了一个搜索值。您甚至可以不使用它。

    //Service.ts

    import {catchError, map, tap } from 'rxjs/operators';
    import {throwError} from 'rxjs';
    import { HttpClient, HttpErrorResponse} from '@angular/common/http';
    
    private employeeUrl="https://api.employee.new/dept/value.json?search=city:"
    getdata(selectedtype): Observable<employee[]> {
    return this.http.get<employee[]>(this.employeeUrl+selectedtype)
          .pipe(
      catchError(this.errorHandler)); 
    }
    
    errorHandler(error: HttpErrorResponse)
    {
    return throwError(error.message || 'Server Error')
    }
    
    
    //employeecomponent.ts
    
    employeedata:any=[];
    public errorMsg;
    ngOnInit(){
    this.dataService.getdata(this.search).subscribe(data =>this.employeedata=data,
                                error =>this.errorMsg=error);
    }
    

    //最后可以绑定到Html文件中

    //employeecomponent.html

    <h3>errorMsg</h3>
    

    【讨论】: