Error handling in Angular2

2019-09-11 01:04发布

问题:

I'm working on an Angular 2 service returning data from a restful WebApi backend.

I'm trying to make it gracefully handle the service not being available however I'm getting unexpected information in the error responses.

Here's the code

update(fund, transactionId:string, showToastOnError: boolean, useCorrectUrl: boolean) {
        let options = this.getStartCall();
        options.headers.append("transaction-id", transactionId)
        let url = fundsUrl + (useCorrectUrl ? "" : "breakTheUrl");
        return this._http.put(url, JSON.stringify(fund), options)
            .map(res => res.json())
            //.retry(5)
            .catch(errorResponse => {
                let res = <Response>errorResponse;
                let err = res.json();
                let emsg = err ?
                    (err.error ? err.error : JSON.stringify(err)) :
                    (res.statusText || 'unknown error');
                this._logger.log(emsg, "The fund was not updated", LogLevel.Error, showToastOnError);
                return Observable.throw(emsg);
            })
            .finally(() => this._spinnerService.hide());

    }

When I look at the network traffic I see the 404 error as expected.

My problem is in my catch function.

Here's the value's I'm seeing:

JSON.stringify(errorResponse)

{"_body":{"isTrusted":true},"status":200,"statusText":"Ok","headers":{},"type":3,"url":null}"

errorResponse.json() 

bubbles: false
cancelBubble: false
cancelable: false
currentTarget: XMLHttpRequest
defaultPrevented: false
eventPhase: 2
isTrusted: true
isTrusted: true
lengthComputable: false
loaded: 0
path: Array[0]
position: 0
returnValue: true
srcElement: XMLHttpRequest
target: XMLHttpRequest
timeStamp: 1460990458693
total: 0
totalSize: 0
type: "error"
__proto__: XMLHttpRequestProgressEvent

Am I doing something wrong here or is this a bug in Angular2 beta 15?

回答1:

Most of time, you have such a value for an error when the onerror callback is called on the underlying XHR object. See this line in the source code: https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L70.

That said, it shouldn't occur for a 404 status code but rather on an error like net::ERR_NAME_NOT_RESOLVED.

404 status code is handled by the onload callback: https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L37.

I made a test with the beta15 and I can't reproduce your problem.

See this plunkr: https://plnkr.co/edit/SB3KLZlbJT3wm9ATAE0R?p=preview.