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

Skip to content

Commit 424ea34

Browse files
committed
fix(http): Include HTTP status code and headers when HTTP requests errored in httpResource
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()`.
1 parent df42976 commit 424ea34

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';
@@ -353,7 +353,14 @@ class HttpResourceImpl<T>
353353
break;
354354
}
355355
},
356-
error: (error) => send({error}),
356+
error: (error) => {
357+
if (error instanceof HttpErrorResponse) {
358+
this._headers.set(error.headers);
359+
this._statusCode.set(error.status);
360+
}
361+
362+
send({error});
363+
},
357364
complete: () => {
358365
if (resolve) {
359366
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