Angular2 rxjs http.request.catch has weird behavior for some HTTP errors

My http service does not fix some HTTP errors. The catch method has two different response objects (see below).

private fireRequest(request: Request): Observable<any> {
    return this.http.request(request)
    .switchMap((response: Response) => {
        const responseData = response.json() || [];
        return Observable.of(responseData);
    })
    .catch((response: Response) => {
        const res2 = response.json();
        // filters http errors from status 0 errors
        if (response.status && response.status > 0) {
            const res = response.json();
            return Observable.of<any>(res);
        }
        const unexpectedNetworkError = new 
              Error('commons.unexpected_network');
        return Observable.throw(unexpectedNetworkError);
    })
}

Strange error behavior. (even on the chrome network tab I don't see the http body)

// catch 404 error
{ 
  headers: Headers,
  ok: false,
  status: 0,
  statusText : "",
  type : 3,
  url : null,
  _body : ProgressEvent
}

Correct error behavior

// catch 401 error
{ 
  headers: Headers,
  ok: false,
  status: 401,
  statusText : "Unauthorized",
  type : 2,
  url : http://api.service/users,
  _body : { // json body}
}
+4
source share
1 answer

I found out about the browser and its CORS behavior.

a) Substantial challenge

BROWSER                  SERVER
    | ------ preflight ---> |
    | <-- allow GET, PUT -- |
    | ------- GET req ----> |
    | <------ GET res ----- |

b) Failed call with support for 404 instead of 200

BROWSER                SERVER
    | ---- preflight ----> |
    | <------ 404 -------- |
    |                      |
    |                      |

c) No connection to intenet, no response from the server

BROWSER                SERVER
    | ---- preflight ----> X
    |                      |
    |                      |
    |                      |

Whenever you call an api call to a non-existent root, the browser sends a request before the flight (b).

, :

1) Http 404 http 0 . , , .

2) Http 200 404 . .

, .

+4

Source: https://habr.com/ru/post/1675534/


All Articles