From 590399de12cf07ad279d78a8222a46659fbc74ce Mon Sep 17 00:00:00 2001 From: Jonathan Berney Date: Thu, 7 Dec 2017 11:34:17 -0800 Subject: [PATCH] catch errors that happen during onSubmit [#153488986] Signed-off-by: Reid Mitchell --- spec/pivotal-ui-react/form/form_spec.js | 36 ++++++++++++++++++++----- src/react/forms/form.js | 16 +++++------ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/spec/pivotal-ui-react/form/form_spec.js b/spec/pivotal-ui-react/form/form_spec.js index 5cd876160..bd02fe49d 100644 --- a/spec/pivotal-ui-react/form/form_spec.js +++ b/spec/pivotal-ui-react/form/form_spec.js @@ -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) => { @@ -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); }); @@ -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); + }); + }); }); }); diff --git a/src/react/forms/form.js b/src/react/forms/form.js index 6e18b0dfd..26a2c79c7 100644 --- a/src/react/forms/form.js +++ b/src/react/forms/form.js @@ -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; } }