diff --git a/.changeset/thrown-validators-show.md b/.changeset/thrown-validators-show.md new file mode 100644 index 00000000..459c2ba9 --- /dev/null +++ b/.changeset/thrown-validators-show.md @@ -0,0 +1,5 @@ +--- +"@clack/core": patch +--- + +Show errors thrown by a `validate` function (or rejected by an async one) as the validation message instead of crashing the prompt. diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 4b45612c..9d98a5a3 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -277,14 +277,18 @@ export default class Prompt { if (key?.name === 'return' && this._shouldSubmit(char, key)) { if (this.opts.validate) { - const problemResult = runValidation(this.opts.validate, this.value); let problem: string | Error | undefined; - if (problemResult instanceof Promise) { - this.state = 'validating'; - this.render(); - problem = await problemResult; - } else { - problem = problemResult; + try { + const problemResult = runValidation(this.opts.validate, this.value); + if (problemResult instanceof Promise) { + this.state = 'validating'; + this.render(); + problem = await problemResult; + } else { + problem = problemResult; + } + } catch (err) { + problem = err instanceof Error ? err : String(err); } if (problem) { this.error = problem instanceof Error ? problem.message : problem; diff --git a/packages/core/test/prompts/prompt.test.ts b/packages/core/test/prompts/prompt.test.ts index efe73a6f..87cfca6e 100644 --- a/packages/core/test/prompts/prompt.test.ts +++ b/packages/core/test/prompts/prompt.test.ts @@ -516,6 +516,45 @@ describe('Prompt', () => { expect(instance.error).to.equal(''); }); + test('shows errors thrown by a validator as the validation message', () => { + const instance = new Prompt({ + input, + output, + render: () => 'foo', + validate: () => { + throw new Error('validator blew up'); + }, + }); + instance.prompt(); + + instance.value = 'anything'; + input.emit('keypress', '', { name: 'return' }); + + expect(instance.state).to.equal('error'); + expect(instance.error).to.equal('validator blew up'); + }); + + test('shows errors rejected by an async validator as the validation message', async () => { + const instance = new Prompt({ + input, + output, + render: () => 'foo', + validate: async () => { + await waitForTick(); + throw new Error('async validator blew up'); + }, + }); + instance.prompt(); + + instance.value = 'anything'; + input.emit('keypress', '', { name: 'return' }); + + expect(instance.state).to.equal('validating'); + await waitForTick(); + expect(instance.state).to.equal('error'); + expect(instance.error).to.equal('async validator blew up'); + }); + test('ignores keypresses while async validation is pending', async () => { const eventSpy = vi.fn(); let resolveValidation: (problem: string | undefined) => void;