8000 fix(http): Include HTTP status code and headers when HTTP requests er… · angular/angular@d39e09d · GitHub
[go: up one dir, main page]

Skip to content

Commit d39e09d

Browse files
wartabatscott
authored andcommitted
fix(http): Include HTTP status code and headers when HTTP requests errored in httpResource (#60802)
Currently the HTTP status code and headers are only included if the request succeeded. Given status codes convey more information in case of a request error vs. success, this makes it more useful than inspecting what is contained in `.error()`. PR Close #60802
1 parent 54f9269 commit d39e09d

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

packages/common/http/src/resource.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {Subscription} from 'rxjs';
2525

2626
import {HttpRequest} from './request';
2727
import {HttpClient} from './client';
28-
import {HttpEventType, HttpProgressEvent, HttpResponseBase} from './response';
28+
import {HttpErrorResponse, HttpEventType, HttpProgressEvent, HttpResponseBase} from './response';
2929
import {HttpHeaders} from './headers';
3030
import {HttpParams} from './params';
3131
import {HttpResourceRef, HttpResourceOptions, HttpResourceRequest} from './resource_api';
@@ -357,7 +357,14 @@ class HttpResourceImpl<T>
357357
break;
358358
}
359359
},
360-
error: (error) => send({error}),
360+
error: (error) => {
361+
if (error instanceof HttpErrorResponse) {
362+
this._headers.set(error.headers);
363+
this._statusCode.set(error.status);
364+
}
365+
366+
send({error});
367+
},
361368
complete: () => {
362369
if (resolve) {
363370
send({error: new Error('Resource completed before producing a value')});

packages/common/http/test/resource_spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,24 @@ describe('httpResource', () => {
122122
expect(res.statusCode()).toBe(200);
123123
});
124124

125+
it('should return response headers & status when request errored', async () => {
126+
const backend = TestBed.inject(HttpTestingController);
127+
const res = httpResource(() => '/data', {injector: TestBed.inject(Injector)});
128+
TestBed.flushEffects();
129+
const req = backend.expectOne('/data');
130+
req.flush([], {
131+
headers: {
132+
'X-Special': '123',
133+
},
134+
status: 429,
135+
statusText: 'Too many requests',
136+
});
137+
await TestBed.inject(ApplicationRef).whenStable();
138+
expect((res.error() as any).error).toEqual([]);
139+
expect(res.headers()?.get('X-Special')).toBe('123');
140+
expect(res.statusCode()).toBe(429);
141+
});
142+
125143
it('should support progress events', async () => {
126144
const backend = TestBed.inject(HttpTestingController);
127145
const res = httpResource(

0 commit comments

Comments
 (0)
0