Skip to content

Commit

Permalink
feat(ajax): Include the response on instances of AjaxError
Browse files Browse the repository at this point in the history
A non-2xx HTTP response may include a body to provide context to the error. Provide the ability to
retrieve the response from the AjaxError as you would from an AjaxResponse.
  • Loading branch information
ncphillips authored and benlesh committed Sep 19, 2017
1 parent 6d27c30 commit 3f6553c
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions src/observable/dom/AjaxObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,24 +417,7 @@ export class AjaxResponse {
constructor(public originalEvent: Event, public xhr: XMLHttpRequest, public request: AjaxRequest) {
this.status = xhr.status;
this.responseType = xhr.responseType || request.responseType;

switch (this.responseType) {
case 'json':
if ('response' in xhr) {
//IE does not support json as responseType, parse it internally
this.response = xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
} else {
this.response = JSON.parse(xhr.responseText || 'null');
}
break;
case 'xml':
this.response = xhr.responseXML;
break;
case 'text':
default:
this.response = ('response' in xhr) ? xhr.response : xhr.responseText;
break;
}
this.response = parseXhrResponse(this.responseType, xhr);
}
}

Expand All @@ -455,12 +438,37 @@ export class AjaxError extends Error {
/** @type {number} The HTTP status code */
status: number;

/** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */
responseType: string;

/** @type {string|ArrayBuffer|Document|object|any} The response data */
response: any;

constructor(message: string, xhr: XMLHttpRequest, request: AjaxRequest) {
super(message);
this.message = message;
this.xhr = xhr;
this.request = request;
this.status = xhr.status;
this.responseType = xhr.responseType || request.responseType;
this.response = parseXhrResponse(this.responseType, xhr);
}
}

function parseXhrResponse(responseType: string, xhr: XMLHttpRequest) {
switch (responseType) {
case 'json':
if ('response' in xhr) {
//IE does not support json as responseType, parse it internally
return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
} else {
return JSON.parse(xhr.responseText || 'null');
}
case 'xml':
return xhr.responseXML;
case 'text':
default:
return ('response' in xhr) ? xhr.response : xhr.responseText;
}
}

Expand Down

0 comments on commit 3f6553c

Please sign in to comment.