File tree Expand file tree Collapse file tree 2 files changed +16
-1
lines changed Expand file tree Collapse file tree 2 files changed +16
-1
lines changed Original file line number Diff line number Diff line change @@ -191,6 +191,14 @@ export class HttpXhrBackend implements HttpBackend {
191
191
// The parse error contains the text of the body that failed to parse.
192
192
body = { error, text : body } as HttpJsonParseError ;
193
193
}
194
+ } else if ( ! ok && req . responseType === 'json' && typeof body === 'string' ) {
195
+ try {
196
+ // Attempt to parse the body as JSON.
197
+ body = JSON . parse ( body ) ;
198
+ } catch ( error ) {
199
+ // Cannot be certain that the body was meant to be parsed as JSON.
200
+ // Leave the body as a string.
201
+ }
194
202
}
195
203
196
204
if ( ok ) {
Original file line number Diff line number Diff line change @@ -17,7 +17,7 @@ import {MockXhrFactory} from './xhr_mock';
17
17
18
18
function trackEvents ( obs : Observable < HttpEvent < any > > ) : HttpEvent < any > [ ] {
19
19
const events : HttpEvent < any > [ ] = [ ] ;
20
- obs . subscribe ( event => events . push ( event ) ) ;
20
+ obs . subscribe ( event => events . push ( event ) , err => events . push ( err ) ) ;
21
21
return events ;
22
22
}
23
23
@@ -92,6 +92,13 @@ export function main() {
92
92
const res = events [ 1 ] as HttpResponse < { data : string } > ;
93
93
expect ( res . body ! . data ) . toBe ( 'some data' ) ;
94
94
} ) ;
95
+ it ( 'handles a json error response' , ( ) => {
96
+ const events = trackEvents ( backend . handle ( TEST_POST . clone ( { responseType : 'json' } ) ) ) ;
97
+ factory . mock . mockFlush ( 500 , 'Error' , JSON . stringify ( { data : 'some data' } ) ) ;
98
+ expect ( events . length ) . toBe ( 2 ) ;
99
+ const res = events [ 1 ] as any as HttpErrorResponse ;
100
+ expect ( res . error ! . data ) . toBe ( 'some data' ) ;
101
+ } ) ;
95
102
it ( 'handles a json string response' , ( ) => {
96
103
const events = trackEvents ( backend . handle ( TEST_POST . clone ( { responseType : 'json' } ) ) ) ;
97
104
expect ( factory . mock . responseType ) . toEqual ( 'text' ) ;
You can’t perform that action at this time.
0 commit comments