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

Skip to content

Commit 9f31947

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 ea58402 commit 9f31947

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

packages/common/http/src/resource.ts

+9-2
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

+18
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