Skip to content

Commit a1b906f

Browse files
committed
rewrite error-handling for nml import to satisfy flow
1 parent 97810d4 commit a1b906f

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

app/assets/javascripts/libs/utils.js

+22
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,28 @@ const Utils = {
503503
// Big endian
504504
return [a, b, g, r];
505505
},
506+
507+
promiseAllWithErrors: async function<T>(
508+
promises: Array<Promise<T>>,
509+
): Promise<{ successes: Array<T>, errors: Array<Error> }> {
510+
const successOrErrorObjects = await Promise.all(promises.map(p => p.catch(error => error)));
511+
return successOrErrorObjects.reduce(
512+
({ successes, errors }, successOrError) => {
513+
if (successOrError instanceof Error) {
514+
return {
515+
successes,
516+
errors: errors.concat([successOrError]),
517+
};
518+
} else {
519+
return {
520+
successes: successes.concat([successOrError]),
521+
errors,
522+
};
523+
}
524+
},
525+
{ successes: [], errors: [] },
526+
);
527+
},
506528
};
507529

508530
export default Utils;

app/assets/javascripts/oxalis/view/nml_upload_zone_container.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import Store from "oxalis/store";
1313
import type { OxalisState } from "oxalis/store";
1414
import { connect } from "react-redux";
1515
import FormattedDate from "components/formatted_date";
16+
import Utils from "libs/utils";
1617

1718
type State = {
1819
files: Array<*>,
@@ -134,8 +135,9 @@ class NmlUploadZoneContainer extends React.PureComponent<Props, State> {
134135
this.setState({
135136
isImporting: true,
136137
});
138+
137139
try {
138-
const importActions = await Promise.all(
140+
const { successes: importActions, errors } = await Utils.promiseAllWithErrors(
139141
this.state.files.map(async file => {
140142
const nmlString = await readFileAsText(file);
141143
try {
@@ -145,20 +147,19 @@ class NmlUploadZoneContainer extends React.PureComponent<Props, State> {
145147
);
146148
return addTreesAndGroupsAction(trees, treeGroups);
147149
} catch (e) {
148-
return new Error(`"${file.name}" could not be parsed. ${e.message}`);
150+
throw new Error(`"${file.name}" could not be parsed. ${e.message}`);
149151
}
150152
}),
151153
);
152154

153-
const errors = importActions.filter(action => action instanceof Error);
154155
if (errors.length > 0) {
155156
throw errors;
156157
}
157158

158159
// Dispatch the actual actions as the very last step, so that
159160
// not a single store mutation happens if something above throws
160161
// an error
161-
importActions.forEach(action => Store.dispatch(action));
162+
importActions.forEach(actionOrError => Store.dispatch(actionOrError));
162163
} catch (e) {
163164
(Array.isArray(e) ? e : [e]).forEach(e => Toast.error(e.message));
164165
} finally {

0 commit comments

Comments
 (0)