fix: show better error for missing widgets (#3377)

This commit is contained in:
Erez Rokah 2020-03-04 13:53:21 +01:00 committed by GitHub
parent e1f43f0860
commit ff3b62d12f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 1 deletions

View File

@ -147,4 +147,26 @@ describe('registry', () => {
});
});
});
describe('getWidget', () => {
it('should throw on missing widget', () => {
const { getWidget } = require('../registry');
expect(() => getWidget('Unknown')).toThrow(
new Error(
`Could not find widget 'Unknown'. Please make sure the widget name is configured correctly or register it via 'registerwidget'.`,
),
);
});
it('should throw on missing widget and suggest lowercase name', () => {
const { getWidget, registerWidget } = require('../registry');
registerWidget('string', {});
expect(() => getWidget('String')).toThrow(
new Error(`Could not find widget 'String'. Did you mean 'string'?`),
);
});
});
});

View File

@ -113,7 +113,16 @@ export function registerWidget(name, control, preview) {
}
}
export function getWidget(name) {
return registry.widgets[name];
const widget = registry.widgets[name];
if (!widget) {
const nameLowerCase = name.toLowerCase();
const hasLowerCase = !!registry.widgets[nameLowerCase];
const message = hasLowerCase
? `Could not find widget '${name}'. Did you mean '${nameLowerCase}'?`
: `Could not find widget '${name}'. Please make sure the widget name is configured correctly or register it via 'registerwidget'.`;
throw new Error(message);
}
return widget;
}
export function getWidgets() {
return produce(Object.entries(registry.widgets), draft => {