Skip to content

Commit

Permalink
WIP: Handle errors gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
SBoudrias committed Apr 23, 2023
1 parent bbd7a52 commit ddaec71
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
28 changes: 16 additions & 12 deletions packages/core/src/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function createPrompt<Value, Config extends AsyncPromptConfig>(
// TODO: we should display a loader while we get the default options.
const resolvedConfig = await getPromptConfig(config);

return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const done = (value: Value) => {
let len = hooksCleanup.length;
while (len--) {
Expand All @@ -155,18 +155,22 @@ export function createPrompt<Value, Config extends AsyncPromptConfig>(
};

const workLoop = () => {
index = 0;
hooksEffect.length = 0;
handleChange = () => workLoop();

const nextView = view(resolvedConfig, done);
for (const effect of hooksEffect) {
effect();
try {
index = 0;
hooksEffect.length = 0;
handleChange = () => workLoop();

const nextView = view(resolvedConfig, done);
for (const effect of hooksEffect) {
effect();
}

const [content, bottomContent] =
typeof nextView === 'string' ? [nextView] : nextView;
screen.render(content, bottomContent);
} catch (err) {
reject(err);
}

const [content, bottomContent] =
typeof nextView === 'string' ? [nextView] : nextView;
screen.render(content, bottomContent);
};

workLoop();
Expand Down
14 changes: 14 additions & 0 deletions packages/input/test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ describe('input prompt', () => {
await expect(answer).resolves.toEqual('2');
});

it('handle errors in validation gracefully', async () => {
const { answer, events, getScreen } = await render(input, {
message: 'Answer 2 ===',
validate() {
return Promise.reject(new Error('Validation error'));
},
});

events.type('1');
events.keypress('enter');
await expect(answer).rejects.toThrowError('Validation error');
expect(getScreen()).toMatchInlineSnapshot();
});

it('handle default option', async () => {
const { answer, events, getScreen } = await render(input, {
message: 'What is your name',
Expand Down

0 comments on commit ddaec71

Please sign in to comment.