-
-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4057 from reduxjs/feature/4x-error-messages
- Loading branch information
Showing
11 changed files
with
358 additions
and
46 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
{ | ||
"0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.", | ||
"1": "Expected the enhancer to be a function. Instead, received: ''", | ||
"2": "Expected the root reducer to be a function. Instead, received: ''", | ||
"3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.", | ||
"4": "Expected the listener to be a function. Instead, received: ''", | ||
"5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.", | ||
"6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.", | ||
"7": "Actions must be plain objects. Instead, the actual type was: ''. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.", | ||
"8": "Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.", | ||
"9": "Reducers may not dispatch actions.", | ||
"10": "Expected the nextReducer to be a function. Instead, received: '", | ||
"11": "Expected the observer to be an object. Instead, received: ''", | ||
"12": "The slice reducer for key \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.", | ||
"13": "The slice reducer for key \"\" returned undefined when probed with a random type. Don't try to handle '' or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.", | ||
"14": "When called with an action of type , the slice reducer for key \"\" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.", | ||
"15": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.", | ||
"16": "bindActionCreators expected an object or a function, but instead received: ''. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
const fs = require('fs') | ||
const helperModuleImports = require('@babel/helper-module-imports') | ||
|
||
/** | ||
* Converts an AST type into a javascript string so that it can be added to the error message lookup. | ||
* | ||
* Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some | ||
* adjustments | ||
*/ | ||
const evalToString = ast => { | ||
switch (ast.type) { | ||
case 'StringLiteral': | ||
case 'Literal': // ESLint | ||
return ast.value | ||
case 'BinaryExpression': // `+` | ||
if (ast.operator !== '+') { | ||
throw new Error('Unsupported binary operator ' + ast.operator) | ||
} | ||
return evalToString(ast.left) + evalToString(ast.right) | ||
case 'TemplateLiteral': | ||
return ast.quasis.reduce( | ||
(concatenatedValue, templateElement) => | ||
concatenatedValue + templateElement.value.raw, | ||
'' | ||
) | ||
case 'Identifier': | ||
return ast.name | ||
default: | ||
throw new Error('Unsupported type ' + ast.type) | ||
} | ||
} | ||
|
||
/** | ||
* Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a | ||
* smaller bundle size in production for consumers. | ||
* | ||
* If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. | ||
* | ||
* If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a | ||
* an error number index in production or the actual error message in development. This allows consumers using webpak | ||
* or another build tool to have these messages in development but have just the error index in production. | ||
* | ||
* E.g. | ||
* Before: | ||
* throw new Error("This is my error message."); | ||
* throw new Error("This is a second error message."); | ||
* | ||
* After (with minify): | ||
* throw new Error(0); | ||
* throw new Error(1); | ||
* | ||
* After: (without minify): | ||
* throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message."); | ||
* throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message."); | ||
*/ | ||
module.exports = babel => { | ||
const t = babel.types | ||
// When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the | ||
// indexes do not change between builds. | ||
let errorsFiles = '' | ||
if (fs.existsSync('errors.json')) { | ||
errorsFiles = fs.readFileSync('errors.json').toString() | ||
} | ||
let errors = Object.values(JSON.parse(errorsFiles || '{}')) | ||
// This variable allows us to skip writing back to the file if the errors array hasn't changed | ||
let changeInArray = false | ||
|
||
return { | ||
pre: () => { | ||
changeInArray = false | ||
}, | ||
visitor: { | ||
ThrowStatement(path, file) { | ||
const arguments = path.node.argument.arguments | ||
const minify = file.opts.minify | ||
|
||
if (arguments && arguments[0]) { | ||
// Skip running this logic when certain types come up: | ||
// Identifier comes up when a variable is thrown (E.g. throw new error(message)) | ||
// NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed | ||
if ( | ||
path.node.argument.arguments[0].type === 'Identifier' || | ||
path.node.argument.arguments[0].type === 'NumericLiteral' || | ||
path.node.argument.arguments[0].type === 'ConditionalExpression' || | ||
path.node.argument.arguments[0].type === 'CallExpression' | ||
) { | ||
return | ||
} | ||
|
||
const errorMsgLiteral = evalToString(path.node.argument.arguments[0]) | ||
|
||
if (errorMsgLiteral.includes('Super expression')) { | ||
// ignore Babel runtime error message | ||
return | ||
} | ||
|
||
// Attempt to get the existing index of the error. If it is not found, add it to the array as a new error. | ||
let errorIndex = errors.indexOf(errorMsgLiteral) | ||
if (errorIndex === -1) { | ||
errors.push(errorMsgLiteral) | ||
errorIndex = errors.length - 1 | ||
changeInArray = true | ||
} | ||
|
||
// Import the error message function | ||
// Note that all of our error messages are in `src`, so we can assume a relative path here | ||
const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( | ||
path, | ||
'./utils/formatProdErrorMessage', | ||
{ nameHint: 'formatProdErrorMessage' } | ||
) | ||
|
||
// Creates a function call to output the message to the error code page on the website | ||
const prodMessage = t.callExpression( | ||
formatProdErrorMessageIdentifier, | ||
[t.numericLiteral(errorIndex)] | ||
) | ||
|
||
if (minify) { | ||
path.replaceWith( | ||
t.throwStatement( | ||
t.newExpression(t.identifier('Error'), [prodMessage]) | ||
) | ||
) | ||
} else { | ||
path.replaceWith( | ||
t.throwStatement( | ||
t.newExpression(t.identifier('Error'), [ | ||
t.conditionalExpression( | ||
t.binaryExpression( | ||
'===', | ||
t.identifier('process.env.NODE_ENV'), | ||
t.stringLiteral('production') | ||
), | ||
prodMessage, | ||
path.node.argument.arguments[0] | ||
) | ||
]) | ||
) | ||
) | ||
} | ||
} | ||
} | ||
}, | ||
post: () => { | ||
// If there is a new error in the array, convert it to an indexed object and write it back to the file. | ||
if (changeInArray) { | ||
fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2)) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.