Skip to content

Commit

Permalink
catch errors that happen during onSubmit [#153488986]
Browse files Browse the repository at this point in the history
Signed-off-by: Reid Mitchell <rmitchell@pivotal.io>
  • Loading branch information
Jonathan Berney authored and reidmit committed Dec 7, 2017
1 parent 508997a commit 590399d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
36 changes: 29 additions & 7 deletions spec/pivotal-ui-react/form/form_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,13 @@ describe('Form', () => {
});

describe('when clicking the update button', () => {
let error, onSubmitError, onSubmit, resolve, reject;
let error, errors, onSubmitError, onSubmit, resolve, reject;

beforeEach(() => {
Promise.onPossiblyUnhandledRejection(jasmine.createSpy('reject'));
error = new Error('invalid');
onSubmitError = jasmine.createSpy('onSubmitError');
errors = {name: 'invalid'};
onSubmitError = jasmine.createSpy('onSubmitError').and.returnValue(errors);
subject::setProps({onSubmitError});
onSubmit = jasmine.createSpy('onSubmit');
onSubmit.and.callFake(() => new Promise((res, rej) => {
Expand Down Expand Up @@ -212,12 +213,7 @@ describe('Form', () => {
});

describe('when the submit promise rejects', () => {
let errors;

beforeEach(() => {
Promise.onPossiblyUnhandledRejection(jasmine.createSpy('reject'));
errors = {name: 'invalid'};
onSubmitError.and.returnValue(errors);
reject(error);
MockPromises.tick(2);
});
Expand Down Expand Up @@ -286,6 +282,32 @@ describe('Form', () => {
});
});
});

describe('when onSubmit throws an error', () => {
let caught;

beforeEach(() => {
onSubmit.and.throwError(error);
subject::setProps({onSubmit});
try {
subject.onSubmit();
} catch(e) {
caught = e;
}
});

it('calls the onSubmitError', () => {
expect(onSubmitError).toHaveBeenCalledWith(error);
});

it('sets the errors on the state', () => {
expect(subject.state.errors).toBe(errors);
});

it('re-throws the error', () => {
expect(caught).toBe(error);
});
});
});
});

Expand Down
16 changes: 8 additions & 8 deletions src/react/forms/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,16 +166,16 @@ export class Form extends React.Component {
this.setState({...nextState, errors: (onSubmitError && onSubmitError(e)) || {}});
};

const afterSubmitPromise = onSubmit({initial, current});
if (isPromise(afterSubmitPromise)) {
return afterSubmitPromise.then(onSuccess).catch(onError);
} else {
try {
try {
const afterSubmitPromise = onSubmit({initial, current});
if (isPromise(afterSubmitPromise)) {
return afterSubmitPromise.then(onSuccess).catch(onError);
} else {
return onSuccess(afterSubmitPromise);
} catch (e) {
onError(e);
throw e;
}
} catch (e) {
onError(e);
throw e;
}
}

Expand Down

0 comments on commit 590399d

Please sign in to comment.