Skip to content

Commit 112b77b

Browse files
committed
JS client can handle error responses for streams and blobs
1 parent 99ed275 commit 112b77b

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ JavaScript client for the openEO API.
44

55
[![Build Status](https://travis-ci.org/Open-EO/openeo-js-client.svg?branch=master)](https://travis-ci.org/Open-EO/openeo-js-client)
66

7-
This client is in **version 0.3.1** and supports **openEO API versions 0.3.0 and 0.3.1**. Legacy versions are available as releases.
7+
This client is in **version 0.3.2** and supports **openEO API versions 0.3.0 and 0.3.1**. Legacy versions are available as releases.
88

99
## Usage
1010
This library can run in a recent browser supporting ECMAScript 2015 or node.js.

openeo.js

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,48 @@ class Connection {
343343
break;
344344
}
345345

346-
return axios(options);
346+
return axios(options).catch(error => {
347+
return new Promise((resolve, reject) => {
348+
if (error.response !== null && typeof error.response === 'object' && error.response.data !== null && typeof error.response.data === 'object' && typeof error.response.data.type === 'string' && error.response.data.type.indexOf('/json') !== -1) {
349+
// JSON error responses are Blobs and streams if responseType is set as such, so convert to JSON if required.
350+
// See: https://github.com/axios/axios/issues/815
351+
try {
352+
switch(options.responseType) {
353+
case 'blob':
354+
const fileReader = new FileReader();
355+
fileReader.onerror = () => {
356+
fileReader.abort();
357+
reject(error);
358+
};
359+
fileReader.onload = () => {
360+
reject(JSON.parse(fileReader.result));
361+
};
362+
fileReader.readAsText(error.response.data);
363+
break;
364+
case 'stream':
365+
const chunks = "";
366+
error.response.data.on("data", chunk => {
367+
chunks.push(chunk);
368+
});
369+
readStream.on("error", () => {
370+
reject(error);
371+
});
372+
readStream.on("end", () => {
373+
reject(JSON.parse(Buffer.concat(chunks).toString()));
374+
});
375+
break;
376+
default:
377+
reject(error);
378+
}
379+
} catch (exception) {
380+
reject(error);
381+
}
382+
}
383+
else {
384+
reject(error);
385+
}
386+
});
387+
});
347388
}
348389

349390
_resetAuth() {
@@ -755,7 +796,7 @@ class File extends BaseEntity {
755796
}
756797
};
757798
if (typeof statusCallback === 'function') {
758-
options.onUploadProgress = function(progressEvent) {
799+
options.onUploadProgress = (progressEvent) => {
759800
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
760801
statusCallback(percentCompleted);
761802
};

0 commit comments

Comments
 (0)