Skip to content

Commit

Permalink
checkPropTypes: add argument that allows external logging
Browse files Browse the repository at this point in the history
When specified, the argument `warningLogger` will be called with the
same arguments as `warning`. Instead of logging errors to the fbjs
warning logger, we are able to handle them externally.

Fixes facebook#34
  • Loading branch information
rufman authored and stephane-arista committed Sep 4, 2019
1 parent d2959d8 commit bfe8ccd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
22 changes: 22 additions & 0 deletions __tests__/PropTypesDevelopmentStandalone-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,27 @@ describe('PropTypesDevelopmentStandalone', () => {
expectInvalidValidatorWarning(PropTypes.exact({ bar: 'true' }), 'string');
expectInvalidValidatorWarning(PropTypes.exact({ bar: null }), 'null');
});

it('calls the passed in warning logger', () => {
const warningLogger = jest.fn()
const propTypes = {
foo(props, propName, componentName) {
throw new Error('some error');
},
};
const props = {foo: 'foo'};
const returnValue = PropTypes.checkPropTypes(
propTypes,
props,
'prop',
'testComponent',
null,
warningLogger,
);

expect(warningLogger).toBeCalledWith('Failed prop type: some error');
expect(returnValue).toBe(undefined);
});
});

describe('resetWarningCache', () => {
Expand All @@ -262,6 +283,7 @@ describe('PropTypesDevelopmentStandalone', () => {
'testComponent',
null,
);

PropTypes.resetWarningCache();
PropTypes.checkPropTypes(
propTypes,
Expand Down
14 changes: 10 additions & 4 deletions checkPropTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ if (process.env.NODE_ENV !== 'production') {
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
function checkPropTypes(typeSpecs, values, location, componentName, getStack, warningLogger) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
Expand Down Expand Up @@ -80,9 +80,15 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {

var stack = getStack ? getStack() : '';

printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
if (warningLogger) {
warningLogger(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
} else {
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
Expand Down

0 comments on commit bfe8ccd

Please sign in to comment.