Skip to content

Commit f3680b5

Browse files
authored
Merge pull request #4057 from reduxjs/feature/4x-error-messages
2 parents 82ad636 + 3ce88dd commit f3680b5

11 files changed

+358
-46
lines changed

errors.json

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"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.",
3+
"1": "Expected the enhancer to be a function. Instead, received: ''",
4+
"2": "Expected the root reducer to be a function. Instead, received: ''",
5+
"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.",
6+
"4": "Expected the listener to be a function. Instead, received: ''",
7+
"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.",
8+
"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.",
9+
"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.",
10+
"8": "Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.",
11+
"9": "Reducers may not dispatch actions.",
12+
"10": "Expected the nextReducer to be a function. Instead, received: '",
13+
"11": "Expected the observer to be an object. Instead, received: ''",
14+
"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.",
15+
"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.",
16+
"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.",
17+
"15": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.",
18+
"16": "bindActionCreators expected an object or a function, but instead received: ''. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?"
19+
}

rollup.config.js

+5
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export default [
3737
extensions,
3838
plugins: [
3939
['@babel/plugin-transform-runtime', { version: babelRuntimeVersion }],
40+
['./scripts/mangleErrors.js', { minify: false }]
4041
],
4142
babelHelpers: 'runtime'
4243
})
@@ -62,6 +63,7 @@ export default [
6263
'@babel/plugin-transform-runtime',
6364
{ version: babelRuntimeVersion, useESModules: true }
6465
],
66+
['./scripts/mangleErrors.js', { minify: false }]
6567
],
6668
babelHelpers: 'runtime'
6769
})
@@ -82,6 +84,7 @@ export default [
8284
babel({
8385
extensions,
8486
exclude: 'node_modules/**',
87+
plugins: [['./scripts/mangleErrors.js', { minify: true }]],
8588
skipPreflightCheck: true
8689
}),
8790
terser({
@@ -111,6 +114,7 @@ export default [
111114
babel({
112115
extensions,
113116
exclude: 'node_modules/**',
117+
plugins: [['./scripts/mangleErrors.js', { minify: false }]]
114118
}),
115119
replace({
116120
'process.env.NODE_ENV': JSON.stringify('development')
@@ -134,6 +138,7 @@ export default [
134138
babel({
135139
extensions,
136140
exclude: 'node_modules/**',
141+
plugins: [['./scripts/mangleErrors.js', { minify: true }]],
137142
skipPreflightCheck: true
138143
}),
139144
replace({

scripts/mangleErrors.js

+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
const fs = require('fs')
2+
const helperModuleImports = require('@babel/helper-module-imports')
3+
4+
/**
5+
* Converts an AST type into a javascript string so that it can be added to the error message lookup.
6+
*
7+
* Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some
8+
* adjustments
9+
*/
10+
const evalToString = ast => {
11+
switch (ast.type) {
12+
case 'StringLiteral':
13+
case 'Literal': // ESLint
14+
return ast.value
15+
case 'BinaryExpression': // `+`
16+
if (ast.operator !== '+') {
17+
throw new Error('Unsupported binary operator ' + ast.operator)
18+
}
19+
return evalToString(ast.left) + evalToString(ast.right)
20+
case 'TemplateLiteral':
21+
return ast.quasis.reduce(
22+
(concatenatedValue, templateElement) =>
23+
concatenatedValue + templateElement.value.raw,
24+
''
25+
)
26+
case 'Identifier':
27+
return ast.name
28+
default:
29+
throw new Error('Unsupported type ' + ast.type)
30+
}
31+
}
32+
33+
/**
34+
* Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a
35+
* smaller bundle size in production for consumers.
36+
*
37+
* If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup.
38+
*
39+
* If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a
40+
* an error number index in production or the actual error message in development. This allows consumers using webpak
41+
* or another build tool to have these messages in development but have just the error index in production.
42+
*
43+
* E.g.
44+
* Before:
45+
* throw new Error("This is my error message.");
46+
* throw new Error("This is a second error message.");
47+
*
48+
* After (with minify):
49+
* throw new Error(0);
50+
* throw new Error(1);
51+
*
52+
* After: (without minify):
53+
* throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message.");
54+
* throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message.");
55+
*/
56+
module.exports = babel => {
57+
const t = babel.types
58+
// When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the
59+
// indexes do not change between builds.
60+
let errorsFiles = ''
61+
if (fs.existsSync('errors.json')) {
62+
errorsFiles = fs.readFileSync('errors.json').toString()
63+
}
64+
let errors = Object.values(JSON.parse(errorsFiles || '{}'))
65+
// This variable allows us to skip writing back to the file if the errors array hasn't changed
66+
let changeInArray = false
67+
68+
return {
69+
pre: () => {
70+
changeInArray = false
71+
},
72+
visitor: {
73+
ThrowStatement(path, file) {
74+
const arguments = path.node.argument.arguments
75+
const minify = file.opts.minify
76+
77+
if (arguments && arguments[0]) {
78+
// Skip running this logic when certain types come up:
79+
// Identifier comes up when a variable is thrown (E.g. throw new error(message))
80+
// NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed
81+
if (
82+
path.node.argument.arguments[0].type === 'Identifier' ||
83+
path.node.argument.arguments[0].type === 'NumericLiteral' ||
84+
path.node.argument.arguments[0].type === 'ConditionalExpression' ||
85+
path.node.argument.arguments[0].type === 'CallExpression'
86+
) {
87+
return
88+
}
89+
90+
const errorMsgLiteral = evalToString(path.node.argument.arguments[0])
91+
92+
if (errorMsgLiteral.includes('Super expression')) {
93+
// ignore Babel runtime error message
94+
return
95+
}
96+
97+
// Attempt to get the existing index of the error. If it is not found, add it to the array as a new error.
98+
let errorIndex = errors.indexOf(errorMsgLiteral)
99+
if (errorIndex === -1) {
100+
errors.push(errorMsgLiteral)
101+
errorIndex = errors.length - 1
102+
changeInArray = true
103+
}
104+
105+
// Import the error message function
106+
// Note that all of our error messages are in `src`, so we can assume a relative path here
107+
const formatProdErrorMessageIdentifier = helperModuleImports.addDefault(
108+
path,
109+
'./utils/formatProdErrorMessage',
110+
{ nameHint: 'formatProdErrorMessage' }
111+
)
112+
113+
// Creates a function call to output the message to the error code page on the website
114+
const prodMessage = t.callExpression(
115+
formatProdErrorMessageIdentifier,
116+
[t.numericLiteral(errorIndex)]
117+
)
118+
119+
if (minify) {
120+
path.replaceWith(
121+
t.throwStatement(
122+
t.newExpression(t.identifier('Error'), [prodMessage])
123+
)
124+
)
125+
} else {
126+
path.replaceWith(
127+
t.throwStatement(
128+
t.newExpression(t.identifier('Error'), [
129+
t.conditionalExpression(
130+
t.binaryExpression(
131+
'===',
132+
t.identifier('process.env.NODE_ENV'),
133+
t.stringLiteral('production')
134+
),
135+
prodMessage,
136+
path.node.argument.arguments[0]
137+
)
138+
])
139+
)
140+
)
141+
}
142+
}
143+
}
144+
},
145+
post: () => {
146+
// If there is a new error in the array, convert it to an indexed object and write it back to the file.
147+
if (changeInArray) {
148+
fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2))
149+
}
150+
}
151+
}
152+
}

src/bindActionCreators.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { kindOf } from './utils/kindOf'
2+
13
function bindActionCreator(actionCreator, dispatch) {
24
return function () {
35
return dispatch(actionCreator.apply(this, arguments))
@@ -32,9 +34,9 @@ export default function bindActionCreators(actionCreators, dispatch) {
3234

3335
if (typeof actionCreators !== 'object' || actionCreators === null) {
3436
throw new Error(
35-
`bindActionCreators expected an object or a function, instead received ${
36-
actionCreators === null ? 'null' : typeof actionCreators
37-
}. ` +
37+
`bindActionCreators expected an object or a function, but instead received: '${kindOf(
38+
actionCreators
39+
)}'. ` +
3840
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
3941
)
4042
}

src/combineReducers.js

+15-20
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,7 @@
11
import ActionTypes from './utils/actionTypes'
22
import warning from './utils/warning'
33
import isPlainObject from './utils/isPlainObject'
4-
5-
function getUndefinedStateErrorMessage(key, action) {
6-
const actionType = action && action.type
7-
const actionDescription =
8-
(actionType && `action "${String(actionType)}"`) || 'an action'
9-
10-
return (
11-
`Given ${actionDescription}, reducer "${key}" returned undefined. ` +
12-
`To ignore an action, you must explicitly return the previous state. ` +
13-
`If you want this reducer to hold no value, you can return null instead of undefined.`
14-
)
15-
}
4+
import { kindOf } from './utils/kindOf'
165

176
function getUnexpectedStateShapeWarningMessage(
187
inputState,
@@ -35,9 +24,9 @@ function getUnexpectedStateShapeWarningMessage(
3524

3625
if (!isPlainObject(inputState)) {
3726
return (
38-
`The ${argumentName} has unexpected type of "` +
39-
{}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
40-
`". Expected argument to be an object with the following ` +
27+
`The ${argumentName} has unexpected type of "${kindOf(
28+
inputState
29+
)}". Expected argument to be an object with the following ` +
4130
`keys: "${reducerKeys.join('", "')}"`
4231
)
4332
}
@@ -69,7 +58,7 @@ function assertReducerShape(reducers) {
6958

7059
if (typeof initialState === 'undefined') {
7160
throw new Error(
72-
`Reducer "${key}" returned undefined during initialization. ` +
61+
`The slice reducer for key "${key}" returned undefined during initialization. ` +
7362
`If the state passed to the reducer is undefined, you must ` +
7463
`explicitly return the initial state. The initial state may ` +
7564
`not be undefined. If you don't want to set a value for this reducer, ` +
@@ -83,8 +72,8 @@ function assertReducerShape(reducers) {
8372
}) === 'undefined'
8473
) {
8574
throw new Error(
86-
`Reducer "${key}" returned undefined when probed with a random type. ` +
87-
`Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
75+
`The slice reducer for key "${key}" returned undefined when probed with a random type. ` +
76+
`Don't try to handle '${ActionTypes.INIT}' or other actions in "redux/*" ` +
8877
`namespace. They are considered private. Instead, you must return the ` +
8978
`current state for any unknown actions, unless it is undefined, ` +
9079
`in which case you must return the initial state, regardless of the ` +
@@ -167,8 +156,14 @@ export default function combineReducers(reducers) {
167156
const previousStateForKey = state[key]
168157
const nextStateForKey = reducer(previousStateForKey, action)
169158
if (typeof nextStateForKey === 'undefined') {
170-
const errorMessage = getUndefinedStateErrorMessage(key, action)
171-
throw new Error(errorMessage)
159+
const actionType = action && action.type
160+
throw new Error(
161+
`When called with an action of type ${
162+
actionType ? `"${String(actionType)}"` : '(unknown type)'
163+
}, the slice reducer for key "${key}" returned undefined. ` +
164+
`To ignore an action, you must explicitly return the previous state. ` +
165+
`If you want this reducer to hold no value, you can return null instead of undefined.`
166+
)
172167
}
173168
nextState[key] = nextStateForKey
174169
hasChanged = hasChanged || nextStateForKey !== previousStateForKey

0 commit comments

Comments
 (0)