Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thrown-validators-show.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 11 additions & 7 deletions packages/core/src/prompts/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,14 +277,18 @@ export default class Prompt<TValue> {

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;
Expand Down
39 changes: 39 additions & 0 deletions packages/core/test/prompts/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>({
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<string>({
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;
Expand Down